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(N)    空间O(N) 用一个HASHTABLE做检测
     * 时间O(NLGN) 空间O(N) 排序后从两边往中间查找,用O(N)空间存储排序前的INDEX。
     * 如果numbers有序,用第二种更好
     **/
    public class Solution {
        public int[] twoSum(int[] numbers, int target) {
            int len = numbers.length;
            assert(len >= 2);
            
            int[] ret = new int[2];
            HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
            
            for(int i = 0; i < len; i++){
                if( !map.containsKey(numbers[i]) ){
                    map.put(target - numbers[i], i);       
                }
                
                if( map.containsKey(numbers[i]) ){        
                    int idx = map.get(numbers[i]);
                    if(idx < i){
                        ret[0] = idx + 1;  
                        ret[1] = i + 1;
                    }
                }
            }
            
            return ret;
        }
    }
  • 相关阅读:
    LintCode: Climbing Stairs
    LintCode: Binary Tree Postorder Traversal
    LintCode: Binary Tree Preorder Traversal
    LintCode: Binary Tree Inorder Traversal
    Lintcode: Add Two Numbers
    Lintcode: Add Binary
    LintCode: A + B Problem
    LintCode: Remove Linked List Elements
    LintCode:Fibonacci
    Lintcode开刷
  • 原文地址:https://www.cnblogs.com/23lalala/p/3506903.html
Copyright © 2011-2022 走看看