Two Sum-LeetCode-弱菜進擊之路

下面是我copy過來的原題!據說leetcode裏面好多編程題目都是BAT的筆試題,所以爲了校招 我就拿來練手了!

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) 需要注意的是!這裏的返回值起始不是0 開始的!


然後呢!這是我自己寫的一個小小代碼!

之前我嘗試不用hash 直接嵌套兩個for循環 結果就是悲劇的time out!次奧 好吧,那我就換成hash!你贏了!

下面的代碼我沒有註釋= = 我這樣的菜鳥都能看懂 也許大家就更加OK了!大笑


import java.util.HashMap;



public class Solution {

	public int[] twoSum(int[] numbers, int target) {
		int indices[] = new int[2];
		int temp;
		
		HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
		
		for (int i = 0; i < numbers.length; i++) {
			map.put(numbers[i],i);
		}
		for (int i = 0; i < numbers.length; i++) {
			if(map.get(target-numbers[i])!=null && map.get(target-numbers[i])!=i){
				indices[0] = i + 1;
				indices[1] = map.get(target-numbers[i])+1;
				if(indices[0]>indices[1]){
					temp = indices[0];
					indices[0] = indices[1];
					indices[1] = temp;
				}
			}
			else
				continue;
		}
		
		
		
		return indices;
    }
}

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