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;
        }
    }
  • 相关阅读:
    go 正则表达式
    go 发送邮件
    beego 定时任务
    go 字符串操作
    BARTScore试试
    《A method for detecting text of arbitrary shapes in natural scenes that improves text spotting》笔记
    CPM-2
    Foxmail配置qq邮箱
    声音克隆MockingBird
    多模态摘要综述
  • 原文地址:https://www.cnblogs.com/mrpod2g/p/4305263.html
Copyright © 2011-2022 走看看