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;
        }
    }
  • 相关阅读:
    期权标的概率密度函数
    Girsanov Theorem
    拉马努金恒等式
    波动率的三类模型
    stack(栈) and heap(堆)
    covar of lognormal variables
    BS 相关的一些近似公式
    布朗运动的一些特殊性质
    排序算法
    Mac node.js
  • 原文地址:https://www.cnblogs.com/yeek/p/3486536.html
Copyright © 2011-2022 走看看