标签:ems script [1] tps return ice share key hashmap
167. Two Sum II - Input array is sorted
题目大意:和Two Sum一样,这里给出的数组是有序的
思路:target - nums[i],这样就实现了降维了
Java实现:
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i])) {
result[1] = i + 1;
result[0] = map.get(target - nums[i]) + 1;
return result;
}
map.put(nums[i], i);
}
return result;
}
别人的实现:
public int[] twoSum(int[] num, int target) {
int[] indice = new int[2];
if (num == null || num.length < 2) return indice;
int left = 0, right = num.length - 1;
while (left < right) {
int v = num[left] + num[right];
if (v == target) {
indice[0] = left + 1;
indice[1] = right + 1;
break;
} else if (v > target) {
right --;
} else {
left ++;
}
}
return indice;
}
67. Two Sum II - Input array is sorted - LeetCode
标签:ems script [1] tps return ice share key hashmap
原文地址:https://www.cnblogs.com/okokabcd/p/9489532.html