[leetcode] 1. Two Sum
来源:互联网 发布:淘宝刷票会被发现吗 编辑:程序博客网 时间:2024/05/31 19:15
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].
在数组中,找出相加和为target
的数的数组下标(题目假设只有一个解,也就是数组每个元素唯一)
主要是利用的hash的思想,保存下标位置,查找时间为O(1),而不用每次去遍历数组。
public class Solution { public int[] twoSum(int[] nums, int target) { int[] result = new int[]{0,0};//返回值 Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i=0;i<nums.length;++i){ if(map.containsKey(target - nums[i])){ //如果之前的数中有和num[i]相加为target的数 //返回结果 result[0] = map.get(target-nums[i]); result[1] = i; break; }else{ //把位置记录到map中 map.put(nums[i], i); } } //System.out.println(result[0]+" "+result[1]); return result; }}
0 0
- LeetCode 1. Two Sum
- [LeetCode]1.Two Sum
- LeetCode 1.Two Sum
- LeetCode --- 1. Two Sum
- [Leetcode] 1. Two Sum
- leetcode---1.Two sum
- [Leetcode] 1. Two Sum
- LeetCode 1.Two Sum
- LeetCode 1.Two Sum
- LeetCode 1.Two Sum
- 【LeetCode]1.Two Sum
- LeetCode 1.Two Sum
- leetcode 1. Two Sum
- [leetcode] 1. Two Sum
- leetcode 1. Two Sum
- Leetcode- 1. Two Sum
- LeetCode-1.Two Sum
- Leetcode 1. Two Sum
- 清除eclipse中 Launch configuration的历史记录
- Quartz入门Demo(三)之TriggerListener 和 JobListener
- 美团二面
- hdu1080(带权值最长上升子序列)
- 分针网—IT教育: 调皮的JavaScript
- [leetcode] 1. Two Sum
- Oracle 使用OUT参数创建/调用存储过程
- HttpStatus各种状态
- axis2 打包 aar文件
- ionic cordovaCamera拍照上传服务器
- 关于jQuery.template的学习总结
- 逆向分析 Android 程序
- 28. Implement strStr()
- HDU1253 胜利大逃亡(BFS)