image.png
image.png
image.png image.png
image.png image.png
image.png
image.png
image.png
image.png
image.png image.png
image.png
public class TwoSumDemo {
/**
* 通过双重循环遍历数组中所有元素的两两组合
* 当出现符合的就放回两个元素的下标
* @param nums
* @param target
* @return
*/
public static int[] twoSum1(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (target - nums[i] == nums[j]) {
return new int[]{i, j};
}
}
}
return null;
}
public static void main(String[] args) {
int[] nums = new int[]{2, 7, 11, 15};
int target = 9;
int[] myIndex = twoSum1(nums, target);
assert myIndex != null;
for (int el : myIndex) {
System.out.println(el);
}
}
}
更优算法
image.pngpublic static int[] twoSum2(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int partnerNumber = target - nums[i];
if (map.containsKey(partnerNumber)) {
return new int[]{map.get(partnerNumber), i};
}
map.put(nums[i], i);
}
return null;
}
网友评论