[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]; } }
阅读全文
0 0
- [LeetCode]习题1
- Leetcode习题(1)
- LeetCode习题记录(1)Two Sum
- Leetcode习题: SingleNumber II
- Leetcode习题: SingleNumber II
- Leetcode习题: Two Sum
- Leetcode习题:3Sum
- Leetcode习题:Distinct Subsequences
- [LeetCode]习题2
- [LeetCode]习题3
- [LeetCode]习题4
- [LeetCode]习题5
- Leetcode习题:Divide Two Integers
- Leetcode习题-Reverse Integer
- Leetcode习题:Insertion Sort List
- Leetcode习题:Pow(x, n)
- leetcode习题代码(经常更新)
- LeetCode 算法习题 第一周
- loadrunner Web_类函数之web_map_area()
- cocos2d-x3.14_Android环境搭建
- 数据结构题回顾与总结 (1) pat pop sequence
- 前缀式计算
- java设计模式的分类
- [LeetCode]习题1
- tensorflow基础使用5
- javaSE 构造方法
- bzoj1008: [HNOI2008]越狱(快速幂)
- 中国古代史
- loadrunner Web_类函数之web_radio_group()
- MYSQL (三)
- Java比较器描述
- C++头文件和源文件的关系以及makefile文件