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;
        }
    }
  • 相关阅读:
    ASP的生成指定格式的GUID
    Principle
    Email icon generator
    Google 's Gmail
    防火墙
    注释
    对敏捷开发方法的一些疑问
    Faq about multimedia
    BSTR、char*和CString转换
    dshow配置环境vc6
  • 原文地址:https://www.cnblogs.com/yeek/p/3486536.html
Copyright © 2011-2022 走看看