LeetCode第[1]题(Java):Two Sum 标签:Array
题目:
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, and you may not use the same element twice.
翻译:
给定一组整数,两个数字的返回索引,它们的和会等于一个特定的数。
您可能假设每个输入都有一个解决方案,但是你不能使用同一个元素两次。(好吧一开始英语弱鸡的我也没懂,后来编程的时候想到的解释:同一个数不能通过自加而得到目标数)
第一遍编写:74ms
class Solution {
public int[] twoSum(int[] nums, int target) {
Set<Integer> resultSet = new HashSet<Integer>();
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) { // 就是这里想到一个数自加,所以应该从i+1开始。
if (nums[i] + nums[j] == target) {
resultSet.add(i);
resultSet.add(j);
}
}
}
int[] result = new int[resultSet.size()];
for (int i = 0; i < result.length; i++) {
result[i] = (Integer) resultSet.toArray()[i];
}
return result;
}
}
好吧,第一次刷题,隐隐小激动,一开始确实没看清题目。。
看清题目后第一次:46ms 时间复杂度:O(n2)
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
result[0] = i;
result[1] = j;
break;
}
}
}
return result;
}
}
自己看着都觉得菜的很。。竟然用了嵌套for。。
下面是参考答案:12ms 时间复杂度:O(n)
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
int[] result = new int[2]; for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i])) {
result[0] = map.get(target - nums[i]);
result[1] = i; // 此时 i 对应的元素还没有放进去。
return result;
}
map.put(nums[i], i);
}
return result;
}
原来用了HashMap来定位两者有某种关系的数。。快了一倍多。。
结论:
当需要使用嵌套for循环来查找或者定位的时候,尽量优先考虑是否能使用Map(存储每一个值作为key,相应下标作为value)
使用 map.containsKey(__) 方法来进行定位
2018-1-8更新:今天做到3sum想到和这里的2sum联系,
3sum:求所有的相加为目标值的数组,
2sum:一旦查找到相加为目标值的俩数组则直接返回俩下标,程序直接结束(仅一组)
现在将2sum的题目改为如下:
给定一个n个整数的数组,在数组中找到和为目标值的所有唯一的两个元素组合【注意不是求下标】
注意:答案集不能包含重复的双胞胎。
测试用例:{1,4,-1,2,-1,0} 1 结果:[[0, 1], [-1, 2]]
{3,2,3,4,1,4,5,5} 8 结果:[[4, 4], [3, 5]]
Code1:时间复杂度:O(N) 【其实应该是Arrays.sort(num)的复杂度】
public static List<List<Integer>> twoSumAll(int[] num, int target) {
Arrays.sort(num); // 将所有相同元素挨在一起
List<List<Integer>> res = new LinkedList<List<Integer>>();
Set<Integer> set = new HashSet<Integer>(); // 不需要下标,并且需要元素唯一,所以采用Set
for (int i = 0; i < num.length; i++) {
if (set.contains(target - num[i])) {
res.add(Arrays.asList(target - num[i], num[i]));
set.remove(target - num[i]); // 防止后续重复元素继续利用此值(因为已经排序,后面不会再有前面的值,不需要再remove(num[i]))
}
set.add(num[i]);
}
return res;
}
此方法仍然采用上面2sum的思想,利用contains()函数减少一次循环,注意Set的remove使答案避免了”双胞胎数组“
下面采用第15题的3sum的‘’双指针相向移动‘’的思想进行算法编写:
Code2:时间复杂度:O(N) 【其实应该是Arrays.sort(num)的复杂度】
public static List<List<Integer>> twoSumAll2(int[] num, int target) {
Arrays.sort(num);
List<List<Integer>> res = new LinkedList<List<Integer>>();
int left = 0;
int right = num.length - 1;
while (left < right) {
if (num[left] + num[right] == target) {
res.add(Arrays.asList(num[left], num[right]));
while (left < right && num[left] == num[left+1]) left++;
while (left < right && num[right] == num[right-1]) right--;
left++;
right--;
} else if (num[left] + num[right] < target) {
left++;
} else {
right--;
}
}
return res;
}
双指针相向移动:利用了 已排序数组 和 所查找的两个数的和为定值 这两个性质
这两个性质如果联合一起用的话………………duang!!!
在已排序数组两端指针所指数之和如果小于目标值,只需要移动左边的指针,否则只需要移动右边的指针
【还看不懂可以自己打草稿试试,或者看我这个博客:LeetCode第[15]题(Java):3Sum 标签:Array】
结论:在求和为目标数时,求下标——HashMap;
求具体组合值——前后指针;
LeetCode第[1]题(Java):Two Sum 标签:Array的更多相关文章
- LeetCode第[18]题(Java):4Sum 标签:Array
题目难度:Medium 题目: Given an array S of n integers, are there elements a, b, c, and d in S such that a + ...
- LeetCode第[15]题(Java):3Sum 标签:Array
题目难度:Medium 题目: Given an array S of n integers, are there elements a, b, c in S such that a + b + c ...
- LeetCode第[88]题(Java):Merge Sorted Array(合并已排序数组)
题目:合并已排序数组 难度:Easy 题目内容: Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as ...
- LeetCode第[1]题(Java):Two Sum (俩数和为目标数的下标)——EASY
题目: Given an array of integers, return indices of the two numbers such that they add up to a specifi ...
- LeetCode第[46]题(Java):Permutations(求所有全排列) 含扩展——第[47]题Permutations 2
题目:求所有全排列 难度:Medium 题目内容: Given a collection of distinct integers, return all possible permutations. ...
- LeetCode第[16]题(Java):3Sum Closest 标签:Array
题目难度:Medium 题目: Given an array S of n integers, find three integers in S such that the sum is closes ...
- LeetCode第[4]题(Java):Median of Two Sorted Arrays 标签:Array
题目难度:hard There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median ...
- LeetCode第[11]题(Java):Container With Most Water 标签:Array
题目难度:Medium Given n non-negative integers a1, a2, ..., an, where each represents a point at coordina ...
- LeetCode第[5]题(Java):Longest Palindromic Substring 标签:String、动态规划
题目中文:求最长回文子串 题目难度:Medium 题目内容: Given a string s, find the longest palindromic substring in s. You ma ...
随机推荐
- .NET Core 已经实现了PHP JIT,现在PHP是.NET上的一门开发语言
12月23日,由开源中国联合中国电子技术标准化研究院主办的2017源创会年终盛典在北京万豪酒店顺利举行.在本次大会上,链家集团技术副总裁.PHP 开发组核心成员鸟哥发表了以 " PHP Ne ...
- 以流方式读写文件:文件菜单打开一个文件,文件内容显示在RichTexBox中,执行复制、剪切、粘贴后,通过文件菜单可以保存修改后的文件。
MainWindow.xaml文件 <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&q ...
- 关于SQLALCHEMY之(一)
SQLALCHEMY是一个不可靠的方案.对于初级开发者而言,并不如SQL语句来得简明. 或者说,我不知道是不是所有的ORM数据库对象映射方案都存在这么一种情况.纯以开发逻辑而言.下述两段代码的结论是一 ...
- IntelliJ IDEA创建java项目
IntelliJ IDEA创建java项目 进入到IntelliJ IDEA启动界面,点击Create New Project 2.这样就进入到了创建项目页面,这里可以创建好多项目,这里我们以java ...
- 此地址使用了一个通常用于网络浏览以外目的的端口。出于安全原因,Firefox 取消了该请求。
火狐无法访问本机IIS部署的网站,弹出:此地址使用了一个通常用于网络浏览以外目的的端口.出于安全原因,Firefox 取消了该请求 的解决办法 关于火狐浏览器访问本机IIS部署的网站弹出"此 ...
- springboot命令启动
gradle打jar包命令 jar { doFirst { def jarFiles = ''; configurations.compile.collect { jarFiles += it.nam ...
- DataBase MongoDB高级知识-易使用
MongoDB高级知识-易使用 mongodb是一个面向文档的数据库,而不是关系型数据库.不采用关系模型主要是为了获取更好的扩展性.当然还有其他的一些好处. 与关系型数据库相比,面向文档的数据库不再有 ...
- ToolStrip和MenuStrip控件簡介及常用屬性(转)
ToolStrip和MenuStrip實際上是相同的控件,因為MenuStrip直接派生於ToolStrip.也就是說ToolStrip可以做的工作,MenuStrip也能完成. ToolStrip( ...
- GDB scheduler-locking 命令详解
GDB scheduler-locking 命令详解 GDB> show scheduler-locking //显示线程的scheduler-locking状态GDB> set ...
- [经验分享]WebApi+SwaggerUI 完美展示接口
不喜欢说废话,直接上干货. 第一步: 打开VS IDE ,新建一个WebAPI项目 选择Web .Net FrameWork (如果喜欢使用.Net Core的可以使用.Net Core) 选择Web ...