[LeetCode]Two Sum

来源:互联网 发布:高斯混合聚类算法 编辑:程序博客网 时间:2024/05/21 06:28

题目描述

Given an array of integers, 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.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

找出数组中两个数的和为target的索引值。

解题思路

  1. O(n*m)。两次for循环,找到numbers[i] + numbers[j] = target。时间肯定超时
  2. O(nlogn)。排序,然后两个指针一前一后遍历。因为题中说明了只有一对答案,因此不需要考虑重复的情况。
  3. O(n)。哈希表。将每个数字放在map中,历遍数组,如果出现和数组中的某一个值相加为target的时候,break。(本思路来自网上帖子)

代码

这里列出思路2和思路3的代码

思路2:
public  int[] twoSum(int[] numbers, int target) {    int start = 0,end = numbers.length - 1;    int x,y;List<Node> list = new ArrayList<Node>();for(int i = 0;i < numbers.length;i++){Node node = new Node(numbers[i],i);list.add(node);}Collections.sort(list, new NodeComparator());while(start < end){x = list.get(start).value;y = list.get(end).value;  if(y > target - x){ end--;  } else if(x < target - y){  start++;  } else {  break;  }}int p1 = list.get(start).pos+1;int p2 = list.get(end).pos+1;return new int[]{p1>p2?p2:p1,p1>p2?p1:p2};}

自定义Node类,用于记录索引值。
public class Node {int value;int pos;Node() {value = 0;pos = 0;}Node(int a, int b) {value = a;pos = b;}}

比较接口。
public  class NodeComparator implements Comparator<Node>{@Overridepublic int compare(Node o1, Node o2) {// TODO Auto-generated method stubif(o1.value > o2.value){return 1;} else if(o1.value < o2.value){return -1;}return 0;}}


思路3:
 public int[] twoSum(int[] numbers, int target) {          int len = numbers.length;          assert(len >= 2);                    int[] ret = new int[2];          HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();                    for(int i = 0; i < len; i++){              if( !map.containsKey(numbers[i]) ){                  map.put(target - numbers[i], i);        // save another number              }                            if( map.containsKey(numbers[i]) ){          // check is another number                  int idx = map.get(numbers[i]);                  if(idx < i){                      ret[0] = idx + 1;   // +1 for not zero-based                      ret[1] = i + 1;                  }              }          }           return ret;      }  



0 0
原创粉丝点击