[LeetCode]习题1

来源:互联网 发布:c语言调用windows api 编辑:程序博客网 时间:2024/06/01 09:54

[LeetCode]习题

首先贴上这次LeetCode题的链接https://leetcode.com/problems/two-sum/description/

根据题目要求要在数组中找到两个相加的值等于target的值的索引,并返回一个两个元素的数组。
在没学算法之前,我们正常的反应肯定是用和冒泡排序差不多的方法进行搜寻,这样要进行n+n-1+。。。。+1次比较,这样肯定有违我们对时间复杂度的要求。所以我们可以生成一个hashmap在里面放已经拿出来进行比较后的元素。这样我们对数组只需进行一次遍历,就可以完成任务,虽然可能在空间复杂度上会比之前的方法复杂,可是节省了时间。

下面是解决问题的方法

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