1. Two Sum leetcode java
来源:互联网 发布:java poi导出word文档 编辑:程序博客网 时间:2024/06/05 04:01
题目:
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
给定一个整数数组和一个特定的值,返回相加等于特定值的两个数的索引,假设对每一个输入只有一个答案,相同的元素不可使用两次。
思路:
1.利用hashmap,遍历nums数组,如果nums[i]和hashmap中的某个数相加等于target,得到答案返回,否则,将nums[i]和i作为key和value存入hashmap。
hashmap的containsKey(key)方法,判断集合中是否包含指定的key;get(key)方法判断集合中是否包含指定的key,
put(K key, V value) (可以相同的key值,但是添加的value值会覆盖前面的,返回值是前一个,如果没有就返回null)
class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer,Integer> map=new HashMap<Integer,Integer>(); int [] res=new int[2]; for(int i=0;i<nums.length;i++){ if(map.containsKey(target-nums[i])){ res[0]=map.get(target-nums[i]); res[1]=i; break; } else map.put(nums[i],i); } return res; }}
算法时间复杂度为O(n),containskey时间复杂度为O(1)
2.看到array和target,想到二分法,但是这道题不是舍弃一半在另一半查找,而是先将array排序,设立low和high指针,当low和high的值相加等于target,得到结果返回,当low和high的值相加大于target,high--,当low和high的值相加小于target,low++。注意;需要把得到的两个值在原数组中找到index,因为已经排序了,原先的index已经被打乱。
class Solution { public int[] twoSum(int[] nums, int target) { int [] temp=new int[nums.length]; System.arraycopy(nums,0,temp,0,nums.length); Arrays.sort(temp); int [] res=new int[2]; int [] trueres=new int[2]; int low=0; int high=temp.length-1; while(low<high){ if(temp[low]+temp[high]==target){ res[0]=low; res[1]=high; break; } else if(temp[low]+temp[high]<target) low++; else high--; } int temp1=0; for(int i=0;i<nums.length;i++){ if(nums[i]==temp[low]&&temp1==0){ trueres[0]=i; temp1=1; } else if(nums[i]==temp[high]) trueres[1]=i; } Arrays.sort(trueres); return trueres; }}
注意,如果数组中有重复数字,最后找原index的时候,注意不要找重,可以设置一个temp1.
数组复制方法:System,arraycopy(Object src, int srcPos, Object dest, int destPos, int length);
类似题目:
- [LeetCode java] 1.Two Sum
- LeetCode(java)1. Two Sum
- leetcode 1. Two Sum -----java
- (JAVA)LeetCode 1. Two Sum
- LeetCode 1. Two Sum(Java)
- [LeetCode] 1. Two Sum java
- leetcode 1. Two Sum -----java
- 1. Two Sum leetcode java
- LeetCode: Two Sum (Java)
- [Leetcode] Two Sum (Java)
- 【Leetcode】two sum JAVA
- LeetCode java Two Sum
- Two Sum leetcode Java
- [LeetCode][Java] Two Sum
- leetcode:Two Sum 【Java】
- LeetCode|Two Sum-java
- leetcode Two Sum(Java)
- leetcode-Java-1. Two Sum.java
- 【转】从零开始学习音视频编程技术(二) 音频格式讲解
- 关于对Bootstrap.Table插件选择节点,全选所有子节点的问题?
- Java中的多线程
- 【sort 专题】179. Largest Number
- 前端在https请求的安全配置问题
- 1. Two Sum leetcode java
- SQL注入绕过技巧
- PrintWriter和FileWriter这两个类有什么区别
- Java
- Java Web笔记(三)
- 欢迎使用CSDN-markdown编辑器
- 冒泡排序
- html&css-------图像(11/6)
- 解决Qt5中的QSerialPort分多次接收串口数据的问题