zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    MySQL如何查询两个日期之间的记录
    Android常用权限
    Android如何区别真机和模拟器
    android资源文件说明
    Android文件存取路径
    @SuppressLint("NewApi")和@TargetApi()的区别
    Java注释规范
    启动IpFilterDriver驱动
    IDEA 创建 Spring Boot 多模块项目(Multi Modules)
    Spring Boot 多环境如何配置
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4886803.html
Copyright © 2011-2022 走看看