【LeetCode】1 Two Sum
来源:互联网 发布:景区网络销售专员 编辑:程序博客网 时间:2024/06/05 06:56
HashMap
/** * Given an array of integers, find two numbers such that they add up to a * specific target number. * <p> * 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. * <p> * You may assume that each input would have exactly one solution. * <p> * Input: numbers={2, 7, 11, 15}, target=9 Output: index1=1, index2=2 */public class Solution { public int[] twoSum(int[] nums, int target) { int [] index = new int [2]; Map<Integer,Integer> map = new HashMap<Integer,Integer>(); for(int i=0;i<nums.length;i++) { if(map.containsKey(nums[i])) { index[0] = map.get(nums[i])+1; index[1] = i+1; return index; } else { map.put(target-nums[i], i); } } return index; }}
O(n2) runtime, O(1) space – Brute force:
The brute force approach is simple. Loop through each element x and find if there is another value that equals to target – x. As finding another value requires looping through the rest of array, its runtime complexity is O(n2).
O(n) runtime, O(n) space – Hash table:
We could reduce the runtime complexity of looking up a value to O(1) using a hash map that maps a value to its index.
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
- Two Sum | LeetCode(1)
- [Leetcode]1Two Sum
- leetcode 1 Two Sum
- leetcode #1 Two Sum
- leetcode 1:Two Sum
- LeetCode 1 Two Sum
- leetcode #1 two sum
- UVa - 100 - The 3n + 1 problem
- c#向Access数据库中批量插入大量记录的方法
- Spring+ActiveMQ实现消息的交换
- LeetCode-House Robber-解题报告
- Ubantu开发环境安装部署
- 【LeetCode】1 Two Sum
- 各语言中取整的运用
- git
- ListView中使用单例添加按钮事件监听
- 【原创】win7同局域网下共享文件
- Android studio 启动另一个activity
- linux中内核的一个不错的参数somaxconn
- Spring与事务管理
- 欢迎使用CSDN-markdown编辑器