public class Solution {
public int[] twoSum(int[] nums, int target) {
if (nums == null || nums.length == 0 || nums.length == 1) {
return null;
}
ArrayList<Integer> temp = new ArrayList<Integer>();
for (int i = 0; i < nums.length; i ++) {
for (int j = 0; j < temp.size(); j ++) {
if (temp.get(j) == nums[i]) {
return new int[]{j, i};
}
}
temp.add(target - nums[i]);
}
return null;
}
public int[] twoSum(int[] nums, int target) {
if (nums == null || nums.length == 0 || nums.length == 1) {
return null;
}
ArrayList<Integer> temp = new ArrayList<Integer>();
for (int i = 0; i < nums.length; i ++) {
for (int j = 0; j < temp.size(); j ++) {
if (temp.get(j) == nums[i]) {
return new int[]{j, i};
}
}
temp.add(target - nums[i]);
}
return null;
}
}
hashmap 版本:
用hashmap好处:更小的时间复杂度(hashmap查找更快)
public class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i ++) {
if (map.get(target - nums[i]) != null) {
return new int[] {map.get(target - nums[i]), i};
}
map.put(nums[i], i);
}
return null;
}
}