1. 程式人生 > >lintcode56 - Two Sum - easy

lintcode56 - Two Sum - easy

util () number logs imp int shm {} you

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