Two Sum(两个数字和)
来源:互联网 发布:super() python 编辑:程序博客网 时间:2024/06/03 16:39
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
解题思路
方法1、将每个值存到Map中个,其中key为值,value为其下标;遍历一下所有的数值x,查找target与x的差判断其是否在map中存在,存在则可以直接找到两个的下标。
因为map不能存储两个相同的数值,但数据可能存在有两个数值重复需要对map的value进行处理,将其存成字符串,后面再进行解析。因为map查找数据的复杂度为O(logn),所以整体的时间复杂度为O(nlogn)
方法2、当数据的数值不大的时候可以考虑定义一个大的数组,用空间换时间,即数组flagNum[i]=0,将数值的对应的数组的下标置为1,有多个就进行累加,这样查找的时间复杂度为O(1),整体的时间复杂度为O(n)
public int[] twoSum(int[] nums, int target) { int result[] = new int[2]; int i = 0; Map<Integer,String> numMap = new HashMap<Integer,String>(); for(i = 0; i < nums.length; i++){ if (!numMap.containsKey(nums[i])) { numMap.put(nums[i], i+""); }else{ String t = numMap.get(nums[i]); numMap.put(nums[i], t+","+i);//该值有多个 } } Iterator its = numMap.entrySet().iterator(); while(its.hasNext()){ Map.Entry<Integer,String> entry = (Entry<Integer, String>) its.next(); int num = entry.getKey(); String indexStr[] = entry.getValue().split(","); int distNum = target - num; result[0] = Integer.parseInt(indexStr[0]); if (distNum == num) {//判断是否有其他的该数字 if(indexStr.length > 1 ){ result[1] = Integer.parseInt(indexStr[1]); break; } }else{ if (numMap.containsKey(distNum)) { result[1] = Integer.parseInt(numMap.get(distNum)); break; } } }// System.out.println(result[0]+" "+result[1]); return result; }
目前研究于Spark与Hadoop,群QQ号:521066396(spark,hadoop交流群),欢迎加入共同学习,一起进步~
- Two Sum(两个数字和)
- Two Sum(找出数组中两个和等于指定数字的元素)
- 【LeetCode】Two Sum && 【九度】题目1352:和为S的两个数字
- LeetCode题解--1. Two Sum(和为S的两个数字)
- LeetCode OJ 之 Two Sum(两个数的和)
- LeetCode-Two Sum(编程之美-快速寻找满足条件的两个数字)
- Lettcode | Two Sum(两个数的和等于定值)
- 【LeetCode-面试算法经典-Java实现】【001-Two Sum(求两个数的和)】
- 两个数字之和等于sum
- Sum All Numbers in a Range 返回两个数字和它们之间所有数字的和
- 1. 两数字求和 (Two Sum)
- leetcode-1 Two Sum 找到数组中两数字和为指定和
- 无序数组中找出和为N的两个数 Two Sum
- Two sum(在数组中找两个数,使其和为指定值)
- 1048. Find Coins (25) -- 二分法,寻找和为定值的两个数 (Two Sum - leetcode)
- Two sum 在数组中寻找和为指定值的两个数
- 算法练习1.Two Sum 数组两个和为目标值的下标(map)
- [Leetcode #1]Two Sum 从数组中找出和为特定值的两个数
- Android - Canvas 简单总结
- Leetcode 8. String to Integer (atoi)
- jdk中设计模式的实现
- 由小到大输出这些数字排列
- canvas初体验
- Two Sum(两个数字和)
- BestCoder Round #81 (div.2)-Machine(模拟)
- Android Studio运行或Rebuild的时候报Error:Execution failed for task ':app:compileDebugNdk'.的解决办法
- Android - bitmap简单总结
- Jquery Deferred objects
- 素数求解
- javascript 的 继承(三) 之 组合继承
- 多进程DP
- oralce 释放段空间