zoukankan      html  css  js  c++  java
  • [leetcode]Two Sum

    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

    思路1 : 两层遍历: 对每一个元素查找剩余元素中的是否有满足条件的余数,时间复杂度为O(n^2)

    思路2 :先遍历一遍数组,记录每个数组元素及下标,第二遍遍历的时候,就可以判断数组中是否包含余数了。时间复杂度为O(n),两次遍历

    代码如下:

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

    优化:

    思路3: 一边遍历,时间复杂度O(n)

    在遍历的时候,map的key记录元素的余数,value记录元素下标,当查到map包含某个元素时,即找到第一对满足条件的两个数,同理,该法一边遍历可以找到所有的元素对

    public class Solution {
        public int[] twoSum(int[] numbers, int target) {
            int[] result = new int[2];
            if(numbers == null || numbers.length < 2 ) return result;
            Map<Integer,Integer> map = new HashMap<Integer,Integer>();
            for(int i = 0; i < numbers.length; i++){
                if(map.get(numbers[i]) == null){
                    map.put(target - numbers[i], i + 1);
                }else{
                    result[0] = map.get(numbers[i]);
                    result[1] = i + 1;
                }
            }
            return result;
        }
    }
  • 相关阅读:
    Postgresql修改序列方法 select setval('dataset_id_seq',1,false);
    再谈Elasticsearch全文搜索:你不知道的query_string、match、term、match_phrase的区别
    crosstab(unknown, unknown) does not exist
    Elasticsearch High Level Rest Client 发起请求的过程分析
    提取经过Jar2Exe编译加密的源代码 教程1
    Unity 协程与线程
    box unboxing(装箱 拆箱) C#编程指南
    C++基础笔记(四)C++内存管理
    C++ 箭头-> 双冒号:: 点号.操作符区别
    ref out 方法参数
  • 原文地址:https://www.cnblogs.com/huntfor/p/3841605.html
Copyright © 2011-2022 走看看