MCPcopy Create free account
hub / github.com/crossoverJie/JCSprout / getTwo2

Method getTwo2

src/main/java/com/crossoverjie/algorithm/TwoSum.java:48–59  ·  view source on GitHub ↗

时间复杂度 O(N) 利用Map Key存放目标值和当前值的差值,value 就是当前的下标 每次遍历是 查看当前遍历的值是否等于差值,如果是等于,说明两次相加就等于目标值。 然后取出 map 中 value ,和本次遍历的下标,就是两个下标值相加等于目标值了。 @param nums @param target @return

(int[] nums,int target)

Source from the content-addressed store, hash-verified

46 * @return
47 */
48 public int[] getTwo2(int[] nums,int target){
49 int[] result = new int[2] ;
50 Map<Integer,Integer> map = new HashMap<>(2) ;
51 for (int i=0 ;i<nums.length;i++){
52
53 if (map.containsKey(nums[i])){
54 result = new int[]{map.get(nums[i]),i} ;
55 }
56 map.put(target - nums[i],i) ;
57 }
58 return result ;
59 }
60}

Callers 1

getTwo2Method · 0.95

Calls 2

getMethod · 0.65
putMethod · 0.45

Tested by 1

getTwo2Method · 0.76