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

    public class Solution {
        public int[] twoSum(int[] numbers, int target) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
           Map<Integer,Integer> map = new HashMap<Integer,Integer>();
           int[] result = new int[2];
           int i = 0;
           while(!map.containsKey(numbers[i])){
                int temp = target - numbers[i];
                map.put(temp,i);
                i++;
           }
           result[0] = map.get(numbers[i]) + 1;
           result[1] = i +1;
           return result;
        }
    }
  • 相关阅读:
    关于串联匹配电阻其作用:
    上下拉电阻
    RS232
    常用硬件介绍
    VGA
    JTAG
    [生活]-理财入门
    [Camera] color shading的产生
    [camere] AWB老算法
    Python基础语法知识
  • 原文地址:https://www.cnblogs.com/yeek/p/3486536.html
Copyright © 2011-2022 走看看