来自leetcode的题目(https://leetcode-cn.com/problems/two-sum/):
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
C语言暴力解法:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target,int* returnSize){
int a=0;
int *Size=(int *)malloc(sizeof(int)*2);
for(int i=0;i<numsSize-1;i++)
{
a=target-nums[i];
for(int j=i+1;j<numsSize;j++)
{
if(a==nums[j])
{
Size[0]=i;
Size[1]=j;
*returnSize=2;
return Size;
}
}
}
return 0;
}
JAVA解法:
/*
思路:
1.创建一个map集合,用于存未匹配中的元素,元素做键,索引做值
2.循环传入的数组
3.目标值减去当前值得到差值temp
4.判断map集合中是否有为temp值的键:
判断为true:返回键为temp索引与当前值索引的数组
判断为false:将当前值作为键,索引为值存入map集合
5.没有匹配返回空
*/
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map=new HashMap<>();
for(int i=0;i<nums.length;i++){
int temp=target-nums[i];
if(map.containsKey(temp)){
return new int[]{map.get(temp),i};
}
map.put(nums[i],i);
}
return null;
}
}