Algorithm:Two Sum 之Java实现

题目

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,

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

解法概览

解法1:暴力法

    在leetcode中运行用时: 65 ms, 在Two Sum的Java提交中击败了19.51% 的用户
    复杂度分析:
       时间复杂度:O(n^2)
      空间复杂度:O(1)。 

  解法思路:按大神的推荐,任何一道算法题,都有对应的暴力解法。当实在想不出其他方法时,暴力法就是你的选择。

public int[] twoSum1(int[] nums, int target) {
	    int length = nums.length;
	    for (int i = 0; i < length; ++ i)
	        for (int j = i + 1; j < length; ++ j)
	            if (nums[i] + nums[j] == target)
	                return new int[]{i,j};
	    return null;
	}

解法2:两遍哈希表

     在leetcode中执行用时: 11 ms, 在Two Sum的Java提交中击败了74.59% 的用户
     复杂度分析:
       时间复杂度:O(n)
       空间复杂度:O(n)。 
     解题思路:以空间换时间

public int[] twoSum2(int[] nums, int target) {
		Map<Integer, Integer> map = new HashMap<>();
		for (int i = 0; i < nums.length; i++) {
			map.put(nums[i], i);
		}
		for (int i = 0; i < nums.length; i++) {
			int complement = target - nums[i];
			if (map.containsKey(complement) && map.get(complement) != i) {
				return new int[] { i, map.get(complement) };
			}
		}
		throw new IllegalArgumentException("No two sum solution");
	}

解法3:一遍哈希表

     在leetcode中执行用时: 4 ms, 在Two Sum的Java提交中击败了99.61% 的用户
     复杂度分析:
       时间复杂度:O(n)
       空间复杂度:O(n)。 
     解题思路:所求的两个值,一旦有一个已经在哈希表中,那么另一个值便可在数组遍历过程中找出

public int[] twoSum3(int[] nums, int target) {
		HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
        int[] res = new int[2];
        for (int i = 0; i < nums.length; ++i) {
            if (m.containsKey(target - nums[i])) {
                res[0] = i;
                res[1] = m.get(target - nums[i]);
                break;
            }
            m.put(nums[i], i);
        }
        return res;
	}

文章结束。

猜你喜欢

转载自blog.csdn.net/cysunc/article/details/86666090