{
public int[] twoSum(int[] nums, int target) {
int [] result = new int[2];
for(int i =0 ; i< nums.length;i++){
for(int j = 0; j<i+1;j++){
if(j!=i){
if(nums[i] + nums[j] == target){
result[0] = j;
result[1] = i;
}
}
}
}
return result;
}
}
兩邊hash 空間換時間思想
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
throw new IllegalArgumentException("No two sum solution");
}
}