1. Two Sum
来源:互联网 发布:淘宝上显示喵喵折 编辑:程序博客网 时间:2024/05/29 09:54
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
Solution1 HashMap
6ms 58.80%
public class Solution { public int[] twoSum(int[] nums, int target) { int res [] = new int [2]; Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i = 0; i < nums.length; i++){ if(!map.containsKey(target - nums[i])){ map.put(nums[i], i + 1); }else{ res[0] = map.get(target - nums[i]); res[1] = i + 1; return res; } } return res; }}
Solution 2 Use another array to keep the index of elements in the current array, and sort the array, use two pointers to find the elements.
(findIndex() pre is used to prevent get the same element in the array)
5mw 90.26
public class Solution { public int[] twoSum(int[] nums, int target) { int[] temp = new int[2]; int[] nums_sort = nums.clone(); Arrays.sort(nums_sort); int start = 0; int end = nums_sort.length - 1; while(start < end){ if((nums_sort[start] + nums_sort[end]) == target){ temp[0] = getIndex(nums_sort[start], nums); temp[1] = getIndex(nums_sort[end], nums); if(temp[0] > temp[1]){ int a = temp[1]; temp[1] = temp[0]; temp[0] = a; } break; } else if((nums_sort[start] + nums_sort[end]) < target){ start += 1; } else if((nums_sort[start] + nums_sort[end]) > target){ end -= 1; } } if(start >= end){ temp = null; } return temp; } public int getIndex(int temp, int[] nums){ for(int i=0;i<nums.length;i++){ if(temp == nums[i]) return i+1; } return 0; }}
0 0
- 1. Two Sum && 167. Two Sum II
- LeetCode 1. Two Sum
- [LeetCode]1.Two Sum
- LeetCode 1.Two Sum
- LeetCode --- 1. Two Sum
- 1.Two Sum
- [Leetcode] 1. Two Sum
- leetcode---1.Two sum
- 1.Two Sum
- [Leetcode] 1. Two Sum
- LeetCode 1.Two Sum
- 1. Two Sum
- 1. Two Sum
- 1. Two Sum Ruby
- LeetCode 1.Two Sum
- LeetCode 1.Two Sum
- 1. Two Sum
- 1.Two Sum
- HDU 5620 KK's Steel
- JVM 优化经验总结
- 深入理解JVM性能调优
- Hadoop作业JVM堆优化汇总及JVM复用
- Android性能优化典范 - 第4季
- 1. Two Sum
- HDU 5615 Jam's math problem
- 大数据IMF传奇行动 UBUNTU的SSH SECURECRT不能登陆 与 vmvare net 8的问题解决
- ES6学习——模块化:import和export
- Java数组的复制方法
- 吕鑫MFC学习系列四
- 基本数据结构-heap实现
- 词
- C++中#ifndef/#define/#endif使用详解