leetcode -Two Sum
2015-10-21 09:23
169 查看
链接:https://leetcode.com/problems/two-sum/
题目内容:
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
给出数组numbers 和数字target, 找出数组中两个元素之和为target的元素位置(数组的下标是1-based,即1为第一个元素)。
思路1:使用两层循环,判断满足numers[i]+numbers[j]==target的i和j 。这里时间复杂度是o(n^2)
思路2:使用HashMap,Map的key为numbers中的所有元素,value为元素对应的下标位置。遍历一次数组,如果numbers[i]+某数==target,那么target-numbers[i]一定在数组中,即Map.get(某数)一定存在值,并且j==Map.get(某数)。这样一次遍历就可以找到相对应的两个元素位置。
代码:
题目内容:
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
给出数组numbers 和数字target, 找出数组中两个元素之和为target的元素位置(数组的下标是1-based,即1为第一个元素)。
思路1:使用两层循环,判断满足numers[i]+numbers[j]==target的i和j 。这里时间复杂度是o(n^2)
思路2:使用HashMap,Map的key为numbers中的所有元素,value为元素对应的下标位置。遍历一次数组,如果numbers[i]+某数==target,那么target-numbers[i]一定在数组中,即Map.get(某数)一定存在值,并且j==Map.get(某数)。这样一次遍历就可以找到相对应的两个元素位置。
代码:
public int[] twoSum(int[] nums, int target) { int index[] = new int[2]; int len = nums.length; HashMap map = new HashMap<Integer, Integer>(); for (int i = 0; i < len; i++) { map.put(nums[i], i + 1); } for (int i = 0; i < len; i++) { index[0] = i + 1; int val1 = nums[i]; int val2 = target - val1; if (map.get(val2) != null) { index[1] = (Integer) map.get(val2); if(index[0]==index[1]) { continue; } return index; } } return index; }
相关文章推荐
- 待解决的问题 --- C++
- 通过Erwin的反向工程导入实体 之一
- WindoW 上NTP服务开启设置(摘抄)
- 微信公众平台开发(98) UnionID
- 全球知名图像研究机构网站
- ActiveMQ 消息监听 MessageListener 的使用
- redis通用工具类
- META标签中的<http-equiv>属性值“content-Type”
- Windows 下使用Git管理Github项目
- android 定时拉取数据
- java集成开发环境安装(jdk,eclipse安装)
- 【工具设置】usb001 usb002 (Virtual Printer Port for USB) 有什么区别 打印机驱动装不上 没有usb001
- 三菱plc输出指示灯不亮怎么办(转载)
- 极客学院签约布道师(讲师) ASP.net WebForm介绍视频课程
- 工作中遇到的小问题
- PhotoShop 操作
- 后台开发用到的工具,远程控制Linux工具
- KDE 现状:外观漂亮,但运行欠稳定
- Web工程Deployment Assembly 丢失maven dependencies
- @清晰掉 qsort()