题目描述:
输入一串数组nums,找到数组中和为target的两个值的下标并返回
vue脚手架实现:
mounted() { let a = this.getSum([1, 3, 4, 44, 5], 8) let b = this.getSums([1, 3, 4, 44, 5], 4)
console.log(b); }, methods: {
//方法一 getSum(nums, target) { for(let i=0; i<nums.length; i++){ let anothernum = target - nums[i]; let targetindex = nums.indexOf(target - nums[i]); if(targetindex != -1){ //找到符合条件的元素下标 if(targetindex === i){ //num[i]的值正好是target的1/2 for(let j=i+1; j<nums.length; j++){ if(nums[j] == target/2){ return[i,j] } } }else{ return [i,targetindex] } } } },
//方法二 getSums(nums, target) { for(let i=0; i<nums.length; i++){ for(let j=i+1; j<nums.length; j++){ if(nums[i] + nums[j] == target){ return [i, j] } } } } }