No.1 Two Sum
来源:互联网 发布:php exec函数 不执行 编辑:程序博客网 时间:2024/04/29 20:35
题目
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.
例子
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
思路一
暴力解就可以了,不难看出通过双重循环就可以解决.类似冒泡的循环条件.时间复杂度为O(n^2).
public int[] twoSum(int[] nums, int target) { for(int i=0; i<nums.length-1; i++){ for(int j=i+1; j<nums.length; j++){ if(nums[i] + nums[j] == target){ return new int[]{i,j}; } } } throw new RuntimeException("dont exist solution"); }
思路二
思路一时间复杂度高的原因在于每次计算出target-nums[i]后,需要遍历数组判断是否存在.而这个遍历过程的时间复杂的为O(n).这部分时间是可以通过一个哈希表来缩短为O(1)的.我们只需要在一开始将所有的数值作为key.下标做为value存在哈希表中.然后计算target-nums[i]的值是否在哈希表中即可.时间复杂度O(n).
public int[] twoSum2(int[] nums,int target){ Map<Integer,Integer> map = new HashMap<>(); for(int i=0;i<nums.length;i++) map.put(nums[i],i); for(int i=0;i<nums.length;i++){ int sub = target - nums[i]; if(map.containsKey(sub) && map.get(sub) != i) return new int[]{i, map.get(sub) }; } throw new RuntimeException("dont exist solution"); }
思路三
在思路二中我们是在一开始将所有数据都存在哈希表中.这样就使得一开始就要遍历一次数组.那么我们能不能节省这一部分时间而完成任务呢.实际上是可以的.因为我们在遍历数组的过程中.如果找到匹配项则直接return.如果没有才会遍历下一个.也就是说.如果当我们在循环的过程中.维护这个哈希表.当哈希表中没有当前nums[i]对应的值可以使它相加后等于target时,就将这个nums[i]和i维护到哈希表中.这样可以省一次数组的遍历.时间复杂度O(n).
public int[] twoSum3(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); } throw new RuntimeException("dont exist sulution"); }
0 0
- No.1 Two Sum
- Leetcode NO.1 Two Sum
- LeetCode No.1 Two Sum
- LeetCode--No.1--Two Sum
- leetcode No.1 Two Sum
- LeetCode No.1 Two Sum
- 【LeetCode】No.1 Two Sum
- week1-NO.1 Two Sum
- LeetCode No.1 Two Sum
- LeetCode No.1 Two Sum
- [leetcode NO.1] Two Sum (JAVA)
- leetcode No.1 - two sum题解
- LeetCode(Let it go)-Two Sum-NO.1
- 每日一练之Two sum [leetcode No.1]
- Two sum no map by C
- leetcode NO.371 sum of two integers
- LeetCode 1 - Two Sum
- leetcode 1 Two Sum
- POJ2398——Coneology(计算几何,扫描线)
- Android控件GridView的使用
- 织梦DedeCms调用列表页、文章页评论数和收藏数代码
- Android 半圆矩形的实现
- 一句话证明你开始接触Python
- No.1 Two Sum
- Linux内核中文件操作函数整理
- 织梦DedeCms获取当前页面URL地址的调用方法
- checkedListBoxd的使用。
- 使用jaxws:server 还是使用jaxws:endpoint发布webservice
- 编写嵌套表单
- 获取一个 Byte 的各个 Bit 值
- 利用SQL语句删除或修改织梦DedeCms数据库内容
- 视觉差效果制作总结和案例下载