首页 > 其他 > 详细

lintcode56 - Two Sum - easy

时间:2017-09-09 15:48:20      阅读:256      评论:0      收藏:0      [点我收藏+]
import java.util.Arrays;

public class Solution {
    /*
     * @param numbers: An array of Integer
     * @param target: target = numbers[index1] + numbers[index2]
     * @return: [index1 + 1, index2 + 1] (index1 < index2)
     */
    public int[] twoSum(int[] numbers, int target) {
        // write your code here
        // mergesort- nlogn
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();

        // for loop with binary search -nlog
        for(int i = 0; i < numbers.length; i++){
            if(map.get(numbers[i]) != null){
                int[] twoIdx = {map.get(numbers[i]) +1 , i + 1};
                return twoIdx;
            }
            map.put(target - numbers[i], i);
        }
        int [] twoIdx = {};
        return twoIdx;
    }
    
}

降低时间复杂度用的HashMap方法!
不能用那个binarySearch,因为这里面要你返回的是index,binarysearch使用前要求你一定要sort过,不然他那个折半最后返回的值不会对的。而如果你sort过,那你返回的找到的那个index也和原始数字里所需数字的index不一样了!

lintcode56 - Two Sum - easy

原文:http://www.cnblogs.com/jasminemzy/p/7498388.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!