• 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.

    Input: numbers={2, 7, 11, 15}, target=9
    Output: index1=1, index2=2


    解题思路:

    用HashMap, 但要注意用法的优化,不用将nums[]里所有的数据存储到hashmap里才开始比较,一边存一边比较,若成功则直接返回,能减少时间。

    So the simplest solution using a HashMap is to simply throw all the data in there to start with, then iterate through all of the numbers to see if (target-num) is in there, and if it is, return {lower index, higher index}.

    However, we can cut down on some runtime and code length by doing it in a single for loop.

    We know that the first number is strictly less than the second number (implying not equal), so if we are returning {value found in HashMap, current loop iteration} then we can be certain that we will never have to insert a value in the HashMap before we check if its difference is. Because of this fact, we can do the inserting and checking in the same loop with no issues. This saves a bit on runtime and memory because it means that you are not guaranteed to have to save all of the data in the HashTable at the start.


    Java code:

    public class Solution {
        public int[] twoSum(int[] nums, int target) {
            Map<Integer,Integer> map = new HashMap<Integer,Integer>();
            for(int i = 0; i< nums.length; i++){
                int diff = target - nums[i];
                if(map.containsKey(diff)){
                    int[] result = {map.get(diff), i+1};
                    return result;
                }
                map.put(nums[i],i+1);
            }
            return null;
        }
    }

    Reference:

    1. https://leetcode.com/discuss/19298/very-short-and-simple-java-code-for-two-sum

  • 相关阅读:
    FreeRTOS 动态内存管理
    NODE.JS之我见
    Maven使用详解
    WPF依赖属性详解
    对比MFC资源文件谈谈WPF布局方式
    MAPPING SEGMENTS TO PAGES
    只用一行代码让你的ASP.NET MVC 跑起来
    WPF The Hard Way
    Java判断回文数算法简单实现
    2014让我受益最大的那些书--别找了,都在这里
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4886803.html
Copyright © 2020-2023  润新知