首页 > 其他 > 详细

LeetCode TwoSum

时间:2014-04-21 20:32:40      阅读:618      评论:0      收藏:0      [点我收藏+]

TwoSum

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

 

http://oj.leetcode.com/problems/two-sum/

 

思路:

直接暴力搜索O(N^2)

1、如果没有负数,hash最快

2、先排序,可以将时间复杂度见到O(nlogn),只要保存到set中,就可以快速查找

 

code

bubuko.com,布布扣
    public static int[] twoSum(int[] numbers, int target) {
        int[] indice = new int[2];
        Set<Integer> set = new HashSet<>();
        for (int i : numbers) set.add(i);
        for (int i=0; i<numbers.length; i++) {
            if (set.contains(target - numbers[i])) {
                for (int j=i+1; j<numbers.length; j++) {
                    if (numbers[i] + numbers[j] == target) {
                        indice[0] = i+1;
                        indice[1] = j+1;
                        return indice;
                    }
                }
            }
        }
        return indice;
    }
bubuko.com,布布扣

 

LeetCode TwoSum,布布扣,bubuko.com

LeetCode TwoSum

原文:http://www.cnblogs.com/549294286/p/3678609.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!