class Solution {
public int[] twoSum(int[] nums, int target) {
if(nums.length <= 1){
return null;
}
int[] result = new int[2];
for(int j = 0; j< nums.length-1; j++){
for(int i = nums.length-1; i>0; i--){
if(nums[j] + nums[i] == target && j<i){
result[0] = j;
result[1] = i;
}
}
}
return result;
}
}
执行用时:91 ms, 在所有 Java 提交中击败了5.02%的用户
内存消耗:38.3 MB, 在所有 Java 提交中击败了90.70%的用户
以上是我刚开始的思路,俩次循环,找到相同的值并且保证输出的顺序
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> hashmap = new HashMap<Integer,Integer>();
for(int j = 0; j< nums.length; ++j){
if(hashmap.containsKey(target-nums[j])){
return new int[]{hashmap.get(target-nums[j]),j};
}
hashmap.put(nums[j],j);
}
return new int[0];
}
}
执行用时:2 ms, 在所有 Java 提交中击败了87.59%的用户
内存消耗:38.3 MB, 在所有 Java 提交中击败了91.82%的用户
如上是官方题解,定义了一个HashMap,巧妙的利用了它的键值对和降低了时间复杂度为O(1)