刷Leetcode 之 Two Sum 兩數和

今天在Leetcode開刷,選的是第一個題目。

先上題目:

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.

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

下面是我的解,首先是最耗時間的兩層循環解法:

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        for(int i=0; i<nums.length; i++){
            for(int j=i+1; j<nums.length; j++){
                if(nums[i]+nums[j]==target){
                    int[] ret = new int[]{i,j};
                    Arrays.sort(ret);
                    return ret;
                }
            }
        }
        return null;
    }
}
上面這個解法是最常見的,但是由於是兩層循環需要耗費n*n-1,下圖是AC以後的時間耗費對比:


接着我進行了改進,把兩層循環變爲了兩次循環,藉助HashMap實現:

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
        for(int i=0; i<nums.length; i++){
            map.put(nums[i],i);
        }
        for(int i=0; i<nums.length; i++){
            if(map.containsKey(target-nums[i]) && map.get(target-nums[i])!=i){
                int[] ret = new int[]{i,map.get(target-nums[i])};
                Arrays.sort(ret);
		        return ret;
            }
        }
        return null;
    }
}
下圖是AC以後的時間耗費對比:

接着再次進行了改進,把兩次循環變爲了一次循環,也是藉助HashMap實現,效率有所上升:

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] ret={};
        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
        for(int i=0; i<nums.length; i++){
            if(map.containsKey(target-nums[i]) && map.get(target-nums[i])!=i){
	        	ret= new int[]{i,map.get(target-nums[i])};
	        	break;
            }
            map.put(nums[i],i);
        }
        Arrays.sort(ret);
        return ret;
    }
}
下圖是AC以後的時間耗費對比:



這是我第一次在leetcode上做的第一道題,這是一個開始。



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