首页 > 其他 > 详细

leetcode two sum

时间:2017-12-03 12:40:58      阅读:203      评论:0      收藏:0      [点我收藏+]
 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

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

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