1. Two Sum
来源:互联网 发布:网贷安卓源码 编辑:程序博客网 时间:2024/06/15 16:11
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 thesame element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
第一次提交:failed 代码如下:class Solution { public int[] twoSum(int[] nums, int target) { for(int i=0; i < nums.length; i++){ int rest = target - nums[i]; int find = Arrays.binarySearch(nums,rest); System.out.println("first:"+find); if(find>=0){ if(find==i){ nums[find] = -1; this.out(nums); find = Arrays.binarySearch(nums,rest); System.out.println("rest:"+rest); System.out.println("find:"+find); if(find<0) continue; } System.out.println("ds"); result[0]=i; result[1]=find; return result; } } return result; }问题:如果有相同数字出现有问题。例如当nums=[3,3],target=6时。第二次提交:
public int[] twoSum(int[] nums, int target) { int[] result = new int[2]; List<Integer> temp = new ArrayList<Integer>(); for (int i = 0;i<nums.length;i++){ temp.add(nums[i]); } for(int i=0;i<temp.size();i++){ int rest = target-temp.get(i); if(rest==temp.get(i)) temp.set(i, -1); int find = temp.indexOf(rest); if(find!=-1){ result[0] = i; result[1] = find; return result; } } return result;增加了判断,如果target和target-nums[i]相同就找该数字第二次出现的下标。
但是这种搜索效率不高(why?)
参考比较快的方法:利用hash map:
class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer,Integer> map = new HashMap<>(); for (int i = 0;i<nums.length;i++){ if(map.get(nums[i])!=null){ int[] result = {map.get(nums[i]),i}; return result; } map.put(target-nums[i],i); } int[] result = {}; return result; }}从前往后把target-nums[i]和编号i进行hash,再判断后面的里面是否存在这个数。这样就不用担心数字相同时候先后出现问题。时间复杂度这一块还不懂~~
阅读全文
0 0
- 1. Two Sum && 167. Two Sum II
- LeetCode 1. Two Sum
- [LeetCode]1.Two Sum
- LeetCode 1.Two Sum
- LeetCode --- 1. Two Sum
- 1.Two Sum
- [Leetcode] 1. Two Sum
- leetcode---1.Two sum
- 1.Two Sum
- [Leetcode] 1. Two Sum
- LeetCode 1.Two Sum
- 1. Two Sum
- 1. Two Sum
- 1. Two Sum Ruby
- LeetCode 1.Two Sum
- LeetCode 1.Two Sum
- 1. Two Sum
- 1.Two Sum
- 解决登陆时sql注入漏洞
- 软件工程了解
- 为什么要写博文?
- hive shell常用操作
- 彩色宝石项链C/C++解决
- 1. Two Sum
- KMP算法的一些细节
- JAVA序列化和反序列化的常见格式
- 《.NET 设计规范》第 9 章:常用的设计模式
- 【LeetCode】404. Sum of Left Leaves
- 集合类源码简单阅读(一)(ArrayList)
- MYSQL数据库间同步数据
- 坐标系变换数学基础
- 服务器客户端