<div align=center> <img src="https://img2018.cnblogs.com/blog/1173617/201910/1173617-20191006021559422-1117932709.png"> </div>算法
/** * 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; }
<div align=center> <img src="https://img2018.cnblogs.com/blog/1173617/201910/1173617-20191006022927420-505285184.png"> </div>數組
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!"); } }
class Solution {//一次Hash查表 public int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> map = new HashMap(); for(int i=0;i<nums.length;i++){ int tmp = target - nums[i]; if(map.containsKey(tmp) && map.get(tmp)!=i){ return new int [] { i, map.get(tmp) }; } else { 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!"); } }
<div align=center> <img src="https://img2018.cnblogs.com/blog/1173617/201910/1173617-20191006124050490-767477915.png"> </div>數據結構