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

    O(n2)的时间复杂度无法通过,只能用hashmap<K,V>其中K为number,V为number对应下标,遍历数组,若target-number存在于hashmap中,则返回对应下标,若不存在,则将number和其对应下标存入hashmap中。代码如下:

    public class Solution {
        public int[] twoSum(int[] numbers, int target) {
             int[] re = new int[2];
             Map<Integer,Integer> map = new HashMap<Integer,Integer>();
             int size = numbers.length;
             for(int i=0;i<size;i++) {
                 int tmp = target-numbers[i];
                 if(!map.containsKey(tmp)) {
                    map.put(numbers[i],i);
                 }
                 else {
                     int index = map.get(tmp);
                     re[0] = (i<index?i:index)+1;
                     re[1] = (i>index?i:index)+1;
                 }
             }
             return re;
        }
    }
  • 相关阅读:
    Ext 可编辑的GridPanel
    Ext 选项卡面板TabPanel
    Ext 行模型与Grid视图
    Ext——xtype各组件类型
    Ext 面板(Panel)
    Ext 消息框
    Ext OOP基础
    js设计模式——8.中介者模式
    js设计模式——7.备忘录模式
    mysql数据库优化(四)-项目实战
  • 原文地址:https://www.cnblogs.com/mrpod2g/p/4305263.html
Copyright © 2011-2022 走看看