题目:
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
链接: https://leetcode-cn.com/problems/two-sum
C语言暴力解法:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
for(int i=0; i<numsSize-1; i++){
for(int j=i+1; j<numsSize; j++){
if(nums[i] + nums[j] == target ){
int *a=(int*)malloc(sizeof(int)*2);
a[0]=i;
a[1]=j;
*returnSize=2;
return a;
}
}
}
return 0;
}
暴力求解,前两个for循环和if判断语句很好写出来,重点在于if判断语句中的代码,
题目要求返回两个数组下标,但是C语言中没有类似二元组的数据结构,
而初始代码中提示了 int* returnSize
,所以我们需要返回一个数组,且需要动态分配内存空间。
最后,不要忽略了for循环外面的返回值。
Java暴力解法:
class Solution {
public int[] twoSum(int[] nums, int target) {
int length = nums.length;
int[] retuanArray = new int [2];
for(int i=0; i<length; i++){
for(int j=i+1; j<length; j++){
if(nums[i] + nums[j] == target){
retuanArray[0] = i;
retuanArray[1] = j;
}
}
}
return retuanArray;
}
}