声明
该系列文章参考LeetCode官方题解,开发者题解,以及结合博主自己做题思路完成的,代码全部改为平常写的函数,用主函数自己调用,与做题平台自动化测试有区别。
题目
给定一个整数数组 nums
和一个目标值 target
,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例
题目来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/two-sum 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
思路:
由题可知,返回数组下标,则需要二重循环,用下标0和下标123……比较,然后用下标1和23……比较,直到数组长度减二和数组长度减一比较,这里只是假设每种输入只会对应一个答案,所以可以在最内层直接返回结果了。
代码:
#include<iostream>
using namespace std;
//实现方法
int* twoSum(int *nums, int target) {
for (int i = 0; i < sizeof(nums)-1; i++) {
for (int j = i + 1; j < sizeof(nums); j++) {
if (nums[i] + nums[j] == target) {
int result[] = { i,j };
return result;
}
}
}
return NULL;
}
int main() {
int nums[] = { 2,7,11,15 };
int target = 11;
if (twoSum(nums, target) != NULL) {
cout << "[" << twoSum(nums, target)[0] << "," << twoSum(nums, target)[1] << "]" << endl;
}
else {
cout << "未找到相加等于需求数得数组元素" << endl;
}
system("pause");
return 0;
}