LeetCode01-two sum

題目鏈接地址:https://leetcode.com/problems/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

題目解析:

思路一:採用遍歷的方式對每一個元素相加得到target,時間複雜度O(n^2),但是採用java時,這種方法會超時。

思路二:用hashmap,將每個元素值作爲key,數組索引作爲value存入hashmap,然後遍歷數組元素,在hashmap中尋找與之和爲target的元素。 時間複雜度O(n),空間複雜度O(n)。

對於思路一,採用java時超時,不予採用

對於思路二,詳細代碼如下:

 public static int[] twoSum2(int[] numbers, int target) {
        int[] index=new int[2];
        HashMap<Integer, Integer> map=new HashMap<Integer, Integer>();    
        
        for(int i=0;i<numbers.length;i++){
        	if(!map.containsKey(numbers[i])){
        		map.put(target-numbers[i],i+1);
        		System.out.println("numbers[i]:"+(target-numbers[i])+","+map.get(target-numbers[i]));
        	}else{
        		System.out.println("numbers[i]:"+numbers[i]+","+map.get(numbers[i]));
        		index[0]=map.get(numbers[i]);
        		index[1]=i+1;
        		System.out.println("index[0]"+index[0]);
        		System.out.println("index[1]"+index[1]);
        	}
        }
        return index;
    	
    }




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章