美文网首页
LeetCode第一题Two Sum

LeetCode第一题Two Sum

作者: Diffey | 来源:发表于2016-03-11 22:02 被阅读3842次

一、题目说明

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].
查看原题;
查看我的Github项目地址;
题目很简单:给定一个int数组和一个目标值,返回数组中两个数之和等于目标值的这两个数的索引。

二、解题

2.1 穷举法

这是首先想到的方法,也是最简单直接的方法。
遍历所有两个数之和,找到等于目标值的两个数即可。
代码如下:

public static int[] twoSumByExhaustive(int[] arr, int target) {
    int[] result = new int[2];
    for (int i = 0; i < arr.length; i++) {
        for (int j = i+1; j < arr.length; j++) {
            if (arr[i] + arr[j] == target) {
                result[0] = i;
                result[1] = j;
                break;
            }
        }
    }
    return result;
}

很多算法都可以用穷举法解决,但是作为一个有理想有追求的程序猿,怎可满足于此。

2.2 以空间换时间

问:求两个数之和等于目标值有其他的描述方式么?
答:有,也可以说是求目标值和其中一个数之差在数组中的位置。
于是,很自然我们想到了以空间换取时间,用HashMap存储之差,然后循环数组找到等于差的数。
代码如下:

public static int[] twoSumByMap(int[] nums, int target) {
    int[] result = new int[2];
    Map<Integer, Integer> map = new HashMap();
    for (int i = 0; i < nums.length; i++) {
        if (map.containsKey(nums[i])) {
            result[0] = map.get(nums[i]);
            result[1] = i;
        } else {
            map.put(target - nums[i], i);
        }
    }
    return result;
}

2.3 排序后再查找

问:假如数组是有序的,那么是不是可以更快的找到结果?
答:如果是有序数组,那就可以一趟循环二路查找结果,自然更快。
但是这会有几个问题:
1.排序的消耗?
可以采用快排等高性能排序算法
2.排序后如何返回正确的索引?
可以HashMap存键值对,然后查找索引。但是如果键是相同的数,索引就会出错。
可以copy一份原数组,查找索引。
代码如下:

public static int[] twoSumBySort(int[] nums, int target) {
    int[] result = new int[2];
//  int[] copyNums = nums.clone();
    int[] copyNums = new int[nums.length];
    System.arraycopy(nums, 0, copyNums, 0, nums.length);
//  可以自己写排序算法
    Arrays.sort(nums);
    int sIndex = 0;
    int eIndex = nums.length - 1;
    for (int i = 0; i < nums.length; i++) {
        if (nums[sIndex] + nums[eIndex] == target) {
            result[0] = nums[sIndex];
            result[1] = nums[eIndex];
            break;
        } else if (nums[sIndex] + nums[eIndex] > target) {
            eIndex--;
        } else {
            sIndex++;
        }

    }

    boolean fGit = false;
    for (int i = 0; i < copyNums.length; i++) {
        if (!fGit && copyNums[i] == result[0]) {
            sIndex = i;
            fGit = true;
        } else if (copyNums[i] == result[1]) {
            eIndex = i;
        }
    }
    if (sIndex > eIndex) {
        result[0] = eIndex;
        result[1] = sIndex;
    } else {
        result[0] = sIndex;
        result[1] = eIndex;
    }

    return result;
}

相关文章

网友评论

      本文标题:LeetCode第一题Two Sum

      本文链接:https://www.haomeiwen.com/subject/ngdtlttx.html