【LeetCode】1. Two Sum 解题报告


转载请注明出处:http://blog.csdn.net/crazy1235/article/details/51471280


Subject

出处:https://leetcode.com/problems/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.

Example:

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

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


Explain

该题目给定一个int型数组,和一个target数值。要求找出数组中两个下标对应的数字之和等于target。

返回两个下标组成的数组。


Solution

solution 1

最笨的方法就是循环嵌套。

public static int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];

        if (nums == null || nums.length == 0) {
            return result;
        }

        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    result[0] = i;
                    result[1] = j;
                    return result;
                }
            }
        }
        return result;
    }

该方法时间复杂度较高,O(n²)。
空间复杂度是O(1)。


solution 2

虽然方法一通过了测试,但是时间复杂度较高。
然后看到该题目的提示标签是【Array】【Hash Table】,就想到使用HashMap来存储下标和值。

/**
     * 使用HashMap存储 <br />
     * 
     * @param nums
     * @param target
     * @return
     */
    public static int[] twoSum2(int[] nums, int target) {
        int[] result = new int[2];
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                if (i > map.get(target - nums[i])) {
                    result[0] = map.get(target - nums[i]);
                    result[1] = i;
                } else {
                    result[0] = i;
                    result[1] = map.get(target - nums[i]);
                }
            } else {
                map.put(nums[i], i);
            }
        }
        return result;
    }

注意将 nums[i] 作为key,将下标 i 作为value。
判断map里面是否存在 target-nums[i] 这个key。


bingo~~

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值