Leet Code Medium 1 two sum
来源:互联网 发布:全球域名注册局 编辑:程序博客网 时间:2024/05/16 20:30
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
【算法思路】
1. 暴力搜索,对于每个数 i,在剩下的数组元素中寻找target - i。 时间复杂度 O(n^2)
2. 遍历数组,往hashmap中插入每个数 i 对应的另一个元素target - i (key)及其下标(value)。
当发现某个key已经存在于map中时,说明该数与之前的一个数之和为target,那么找到了对应的index。
【复杂度】
时间 :O(n) 一次遍历
空间 O(n) Hashmap
ps: 严格来说,target-numbers[i]可能溢出int,因此提升为long更鲁棒。
【CODE】
public int[] twoSum(int[] nums, int target) { int len = nums.length; int[] index = new int[2]; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i = 0; i < len; i ++) { if(!map.containsKey(nums[i])) { map.put(target - nums[i] , i); } else { index[0] = map.get(nums[i]) + 1; index[1] = i + 1; break; } } return index; }
- Leet Code Medium 1 two sum
- 【Leet Code- Algorithm】【1-Two Sum】【Python】
- Leet Code Medium 2 add two numbers
- Leet Code Medium 15 3Sum
- Leet Code Medium 16 3Sum Closest
- Leet Code Medium 18 4Sum
- 【Leet Code】64. Minimum Path Sum---Medium
- Leet Code OJ 2. Add Two Numbers [Difficulty: Medium]
- 【Leet Code】209. Minimum Size Subarray Sum---Medium
- Leet Code OJ 15. 3Sum[Difficulty: Medium]
- Leet Code OJ 15. 3Sum[Difficulty: Medium]
- Leet Code OJ 1. Two Sum [Difficulty: Easy]
- Leet Code OJ 1. Two Sum [Difficulty: Easy]
- Leet Code OJ 1. Two Sum [Difficulty: Easy]
- Leet Code OJ 1. Two Sum [Difficulty: Easy]
- [1, Medium, C++] Two Sum
- [leet code] Path Sum
- [leet code] Combination Sum
- NSCoding协议
- Centos7 安装kilo-2 controller(ntp mariadb rabbitmq)
- 零java基础搞定微信Server_5:启用微信公众号开发模式
- Android使用SpannableString进行字符串的分段处理
- java基础—8.IO输入输出流
- Leet Code Medium 1 two sum
- 使用 IndexedDB
- HighCharts 详细使用及API文档说明
- 再谈程序员要注重沟通能力的提升——如何培养起写作的习惯
- 题目:单词搜索
- iOS开发系列课程(06) --- 常用控件介绍
- Java学习笔记,基础总结(二)
- Leetcode 228 Summary Ranges
- 题目:合并k个排序链表