zoukankan      html  css  js  c++  java
  • Two Sum 解答

    Question:

    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

    Solution:

    1. O(n2) runtime, O(1) space – Brute force:

    The brute force approach is simple. Loop through each element x and find if there is another value that equals to target – x. As finding another value requires looping through the rest of array, its runtime complexity is O(n2).

    2. O(n) runtime, O(n) space – Hash table:

    We could reduce the runtime complexity of looking up a value to O(1) using a hash map that maps a value to its index.

     1 public class Solution {
     2     public int[] twoSum(int[] nums, int target) {
     3         Map<Integer, Integer> hm = new HashMap<Integer, Integer>();
     4         int[] result = new int[2];
     5         int length = nums.length;
     6         for (int i = 0; i < length; i++) {
     7             int left = target - nums[i];
     8             if (hm.get(left) != null) {
     9                 result[0] = hm.get(left) + 1;
    10                 result[1] = i + 1;
    11             } else {
    12                 hm.put(nums[i], i);
    13             }
    14         }
    15         return result;
    16     }
    17 }

    3. O(nlogn) runtime, O(1) space - Binary search

    Similar as solution 1, but use binary search to find index2.

    4. O(nlogn) runtime, O(1) space - Two pointers

    First, sort the array in ascending order vwhich uses O(nlogn).

    Then, right pointer starts from biggest number and left pointer starts from smallest number. If two sum is greater than the target number, move the right pointer. If two sum is smaller than the target number, move the left pointer.

  • 相关阅读:
    linux 命令学习
    反编译学习一:Mac下使用dex2jar
    如何删除你的MacOS上的旧版本Java
    使用screen 遇到的多窗口
    dede简略标题调用标签
    JQ实现导航滚动到指定位置变色,并置顶
    JQ实现当前页面导航加效果(栏目页有效)
    wordpress首页调用指定分类下的文章
    作业1#python用列表实现多用户登录,并有三次机会
    python数据类型之间的转换
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4773990.html
Copyright © 2011-2022 走看看