解题报告:#1 Two Sums

来源:互联网 发布:海关信息进出口数据 编辑:程序博客网 时间:2024/06/06 05:10

重回CSDN第一篇。解题报告中所说的注意点或难点仅针对我个人,未必对您适用,您可自行总结自己对一道题的注意点或难点

题目

Two Sums

Assumptions:

开始答题前先和面试官确认:
1. Is it possible that the given array has more than one solutions?
2. Do you want me to just find one solution or all solutions?
3. Any duplicated elements in the array (但跟这题没啥关系)?
4. Do we assume the array always have two or more elements? 如果YES的话一开始的边界情况就不用查啦。

思路一:

通过两个For循环找到两数和为Target时return两数的索引

注意点:
1. 边界情况 nums.length < 1 return null 要写
2. 第二个for loop 的index j 值从 i+1 开始算

解答:

public int[] twoSum(int[] nums, int target) {        int[] ret = new int[2];        if (nums.length < 1)            return null;        for (int i = 0; i < nums.length; i++) {            for (int j = i+1; j < nums.length; j++) {                if (nums[i] + nums[j] == target) {                    ret[0] = i;                    ret[1] = j;                    return ret;                }            }        }        return null;    }

时复:O(n^2)
空复:O(1) 就定义了一个 int[] ret 变量而且这个array只有两个元素

思路二:

用哈希表 nums中的元素为Key ,每个元素的索引为Value 之循环原数组一次得到解
假如有符合的,把values拿出来赋给Int[]得解,假如没有符合的,push 元素到哈希表直到走完数组为止

注意点:
1. Java中HashMap的声明语法 (两年没写Java所以有点生)
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
2. 得值 往map里加东西 containsKey
map.get(key)
map.put(key, value)
map.containsKey(key)

解答:

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

时复:O(n) 只遍历一遍数组
空复:O(n) HashMap的空间复杂度

原创粉丝点击