码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode two sum

时间:2017-12-03 12:55:43      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:ase   hashmap   tco   快排   com   [1]   哈希表   source   one   

 two sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

twosum
  • 方案一使用哈希表

    class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap();
        for(int i = 0; i<nums.length; i++){
            map.put(nums[i], i);
        }
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (map.containsKey(complement) && map.get(complement) != i) {
                return new int[] { i, map.get(complement) };
            }
        }
        return null;
    }
    }
  • 方案二快排

    class Solution {
    public int[] twoSum(int[] nums, int target) {
    
        // corner cases
        if (nums == null || nums.length <= 1) {
            return null;
        }
        int[] nums2 = Arrays.copyOf(nums, nums.length);
        Arrays.sort(nums);
        int left = 0;
        int right = nums.length - 1;
        int a = 0;
        int b = 0;
        while (left < right) {
            long sum = (long) nums[left] + (long) nums[right];
            if (sum == target) {
                a = nums[left];
                b = nums[right];
                break;
            } else if (sum < target) {
                left += 1;
            } else {
                right -= 1;
            }
        }
        // find index 1
        for(int i = 0; i < nums2.length; i++){
            if(nums2[i] == a) {
                left = i;
                break;
            }
        }
        // find index 2
        for(int i = nums2.length - 1; i >= 0; i--){
            if(nums2[i] == b) {
                right = i;
                break;
            }
        }
        return new int[]{Math.min(left, right),Math.max(left, right)};
    
    
    }
    }

leetcode two sum

标签:ase   hashmap   tco   快排   com   [1]   哈希表   source   one   

原文地址:http://www.cnblogs.com/Dyleaf/p/7965720.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!