The idea is to use a map to record array information, one is for values to index to retrieve index results, and the other one is to record each value's appearance times. Leetcode test cases are friendly that don't have duplicates, but it is necessary to clarify and check it.
It is not necessary to sort since sort cost more than O(n). For other cases, since we have outer loop, sort is necessary since the code requires a way to mark out loops. And 3Sum or more are itself cost more than O(n), sort is NOT added any more time complexity.
public class Solution {
public int[] twoSum(int[] numbers, int target) {
if(numbers == null || numbers.length == 0){
return null;
}
Map<Integer, Integer> process = new HashMap<Integer, Integer>();
Map<Integer, Integer> count = new HashMap<Integer, Integer>();
for(int i = 0; i < numbers.length; i++){
process.put(numbers[i], i);
if(count.containsKey(numbers[i])){
count.put(numbers[i], count.get(numbers[i]) + 1);
}else{
count.put(numbers[i], 1);
}
}
int index1 = 0;
int index2 = 0;
for(int i = 0; i < numbers.length; i++){
if(process.containsKey(target - numbers[i]) && (i != process.get(target - numbers[i]) || (i == process.get(target - numbers[i]) && count.get(numbers[i]) > 1))){
index1 = i + 1;
index2 = process.get(target - numbers[i]) + 1;
if(index1 > index2){
int temp = index1;
index1 = index2;
index2 = temp;
}
break;
}
}
int[] result = new int[2];
result[0] = index1;
result[1] = index2;
return result;
}
}
没有评论:
发表评论