您的位置:首页 > 其它

leetcode 1 Two Sum(在无序数组中找两个数之和与目标值相等)

2017-07-17 21:51 344 查看
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

假设,原题要求解可能有一组,这里我们假设解有多组,只输出第一组

public static int[] twoSum(int[] nums, int target) {
// write your code here
int[] index = new int[2];
int flag = 0;
for (int i = 0; i < nums.length-1; i++) {
for (int j = i+1; j < nums.length; j++) {
if(nums[i]+nums[j]==target){
index[0] = i+1;
index[1] = j+1;
}
}
}
return index;
}


这种做法可以输出最后一组,如何在找到第一组解后结束循环呢?

public static int[] twoSum(int[] nums, int target) {
// write your code here
int[] index = new int[2];
int flag = 0;
for (int i = 0; i < nums.length-1; i++) {
for (int j = i+1; j < nums.length; j++) {
if(nums[i]+nums[j]==target){
index[0] = i+1;
index[1] = j+1;
flag = 1;
}if(flag == 1){
break;
}
}if(flag == 1){
break;
}
}
return index;
}

public static int[] twoSum(int[] nums, int target) {
// write your code here
int[] index = new int[2];
for (int i = 0; i < nums.length - 1; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
index[0] = i + 1;
index[1] = j + 1;
}
}
return index;
}
return index;
}


先排序:

public static void getSum(int[] array,int sum){
class innerClass{
int i;
int j;

public innerClass(int i, int j) {
this.i = i;
this.j = j;
}
}
ArrayList<innerClass> list = new ArrayList<>();
Arrays.sort(array);
int low = 0;
int high = array.length - 1;
while (low<high){
if(array[low]+array[high] == sum){
System.out.println("已找到");
list.add(new innerClass(low,high));
}
while (array[low]+array[high]>sum){
high--;
int temp = array[low]+array[high];
if(array[low]+array[high] == sum){
System.out.println("已找到");
list.add(new innerClass(low,high));
}
}
low++;
}

Iterator<innerClass> it = list.iterator();
while (it.hasNext()){
innerClass Result = it.next();
System.out.println(Result.i+" "+Result.j);
}
}

三、更低的时间复杂度
public static void getSumLow(int[] array,int target) {
int[] result = new int[2];
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();//声明并指向一个HashMap集合的引用
for (int i = 0; i < array.length; i++) {//第一次遍历数组,将元素和下标以K-V方式存入hm中
hm.put(array[i], i);
}
for(int i=0;i<array.length;i++) {//第二次遍历数组,查找是否有和为target的元素对
if (hm.containsKey(target - array[i]) && (i != hm.get(target - array[i]))) {
//保证两个元素不是同一个,否则如果target恰好是某个元素的2倍时就不符合题意
//HashMap#boolean containsKey(Object key)
//HashMap#public V get(Object key){...return value;}
result[0] = i;
result[1] = hm.get(target - array[i]);
break;
}
}
System.out.print(result[0]+" "+result[1]);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐