Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
解1:使用嵌套循环进行查询,时间复杂度O(n*n),运行时间72ms
public static int[] twoSum(int[] nums,int target){
int[] result = null;
//时间复杂度:O(n*n)
for (int i = 0;i<nums.length-1;i++){
for (int j=i+1;j<nums.length;j++){
if (nums[i]+nums[j] == target){
result = new int[]{i,j};
}
}
}
return result;
}
解2:利用map.containsKey方法,时间复杂度O(n) ,运行时间8ms
//利用map 8ms
public static int[] twoSum2(int[] nums,int target){
int[] result = null;
HashMap<Integer,Integer> map = new HashMap<>();
for (int i = 0;i < nums.length;i++){//O(n)
if (map.containsKey(target - nums[i])){ //O(1)
result = new int[]{map.get(target - nums[i]),i};
break;
}else {
map.put(nums[i],i);
}
}
return result;
}
解3:使用类二分查找,时间复杂度O(n)+O(n*log(n))+O(n) ,运行时间7ms
//二分查找 7ms
public static int[] twoSum3(int[] nums,int target){
int[] result = null;
int[] copyNums = Arrays.copyOf(nums,nums.length);//O(n)
//排序 使用的是快速排序和优化的合并排序 n*log(n)
Arrays.sort(nums);
int lo = 0;
int hi = nums.length-1;
int m = 0;
//O(n)
while(lo<hi){
m = nums[lo] + nums[hi];
if (m>target){
hi--;
}else if (m<target){
lo++;
}else {
//找到对应的两个值,此时需要找到二者原来的位置
int index1 = 0;
int index2 = 0;
//记录 防止两个指数相等引起的错误
boolean flag1 = false;
boolean flag2 = false;
for (int i=0;i<copyNums.length;i++){ //O(n)
if (copyNums[i] == nums[lo] && !flag1){
index1 = i;
flag1 = true;
}else if (copyNums[i] == nums[hi] && !flag2){
index2 = i;
flag2 = true;
}
}
if (index1<index2) {
result = new int[]{index1, index2};
}else {
result = new int[]{index2,index1};
}
break;
}
}
return result;
}