Happiness is more than pleasure without pain

你只有非常努力,才能看起来毫不费力

导航

Two Sum

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

public class Solution {
    public int[] twoSum(int[] numbers, int target) {
//   int a[] = {0,0};
//     int len=numbers.length;
//     int mid,left,right;
//     for(int i=0;i<len;i++){
//         for(int j=0;j<i;j++){
//             if(numbers[i]+numbers[j]==target){
//                 a[0]=j+1;
//                 a[1]=i+1;
//                 return a;
//             }
//         }
//     }
//         return null;

//第一种暴力解法通过可能是因为case的问题 O(n^2)     第二个for循环换成for(int j=i+1;j<len;j++)就超时了
//用HashMap的原因是containsKey查找效率高O(nlogn)
        int[] a = new int[2];
        HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
        for(int i=0;i<numbers.length;i++){
            if(map.containsKey(target-numbers[i])){
                a[1]=i+1;
                a[0]=map.get(target-numbers[i])+1;
                return  a;
            }
            map.put(numbers[i], i);
        }
        return  null;
        
    }
}

 

posted on 2015-01-08 10:53  believer  阅读(145)  评论(0编辑  收藏  举报