标签:inf 数组 turn public ash target sum solution 遍历
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target){
static int result[2]= {0};
for(int i=0;i<numsSize;i=i++){
for(int j=i+1;j<numsSize;j=j++){ //【trick】“int j=i+1;”而非“int j=0”
if(nums[i]+nums[j]==target){
result[0] = i;
result[1] = j;
return result;
}
}
}
return result;
}
class Solution {
/*
思路:两遍哈希表
推荐文献:
https://baijiahao.baidu.com/s?id=1628609734622761569&wfr=spider&for=pc
*/
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap();
for(int i=0;i<nums.length;i++){
map.put(nums[i],i);
}
for(int j=0;j<nums.length;j++){
int tmp = target - nums[j];
if(map.containsKey(tmp) && map.get(tmp)!=j){
return new int [] { j, map.get(tmp) };
}
}
throw new IllegalArgumentException("No two sum solution!");
}
}
标签:inf 数组 turn public ash target sum solution 遍历
原文地址:https://www.cnblogs.com/johnnyzen/p/11626301.html