package leetcode.xuyi;
import org.junit.*;
import java.util.Arrays;
import java.util.HashMap;
/**
* Created by ethan on 2015/5/2.
*/
public class No1TwoSum {
// 思路1
// 直接双重循环必然超时
// 时间复杂度是O(n2)
// public int[] twoSum(int[] nums, int target) {
// int index1 = 0;
// int index2 = 0;
// boolean flag = false;
// for (int i=0; i<nums.length-1; i++){
// if (flag)
// break;
// int tmp = nums[i];
// for (int j=i+1; j<nums.length; j++){
// if(tmp + nums[j] == target) {
// index1 = i;
// index2 = j;
// flag = true;
// }
// }
// }
// return new int[]{index1+1, index2+1};
// }
// 思路2
// 采用hashMap 其中key值放数值,value放index
// 时间复杂度是O(n)
public int[] twoSum1(int[] nums, int target){
// 注意代码的健壮性,对于参数的requirement
// 认为数组中的不存在重复的元素
if (nums==null || nums.length<2) return null;
HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
for (int i=0; i<nums.length; i++){
hashMap.put(nums[i], i);
}
int[] arr = null;
for (int i=0; i<nums.length; i++){
int num2 = target - nums[i];
Integer index2 = hashMap.get(num2);
// 注意可能找到自己
if (index2!=null && index2!=i){
arr = new int[]{i+1, index2.intValue()+1};
break;
}
}
return arr;
}
// 思路3
// 排序(构造一个class{value,index}, 定义一个comparator), 两个指针一个指头,一个指尾, 不会重复扫描
// 复杂度: O(nlogn)
public int[] twoSum(int[] nums, int target){
if (nums==null || nums.length<2) return null;
// sort
Arrays.sort(nums);
// 寻找合适的index1, index2
int start = 0;
int end = nums.length-1;
int[] arr = null;
while(start < end){
if (nums[start]+nums[end]==target){
arr = new int[]{start+1, end+1};
break;
}else if(nums[start]+nums[end]<target){
start++;
}else{
end++;
}
}
return arr;
}
@Test
public void test1(){
int[] aa = twoSum(new int[]{2,7,11}, 9);
System.out.println(aa[0]+" "+aa[1]);
}
}
Two Sum
最新推荐文章于 2024-04-07 20:30:43 发布