leetcode167 Two SumII java
来源:互联网 发布:embed js控制声音大小 编辑:程序博客网 时间:2024/05/18 02:23
Description
Given an array of integers that is already sorted in ascending order, 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 and you may not use the same element twice.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
解法1
遍历数组,用map存储target-numbers[i],以及i(下标)。
public int[] twoSum(int[] numbers, int target) { int[] res = new int[2]; Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < numbers.length; i++) { if (map.containsKey(numbers[i])) { res[0] = map.get(numbers[i]) + 1; res[1] = i + 1; return res; } else { map.put((target - numbers[i]), i); } } return res; }
解法2
数组是升序排列,设start初始值为0,end初始值为numbers.length-1,先计算numbers中start,end对应两个数的和,如果比target大,end– -,如果比target小,start++。
public int[] twoSum(int[] numbers, int target) { int[] res = new int[2]; int start = 0, end = numbers.length - 1; while (numbers[start] + numbers[end] != target) { if (numbers[start] + numbers[end] > target) { end--; } else { start++; } } res[0] = start + 1; res[1] = end + 1; return res; }
解法3
二分查找法
public int[] twoSum2(int[] numbers, int target) { for (int i = 0; i < numbers.length-1; i++) { int start = i + 1, end = numbers.length - 1; while (start <= end) { int mid = (start + end) / 2; if (numbers[mid] + numbers[i] == target) return new int[]{i + 1, mid + 1}; else if (numbers[mid] + numbers[i] < target) start = mid + 1; else end = mid - 1; } } return new int[2]; }
0 0
- leetcode167 Two SumII java
- 167.[LeetCode]Two SumII
- leetcode(E)two sumII
- LeetCode167.Two Sum II
- leetcode167~Two Sum II
- leetcode167. Two Sum II
- leetcode167: Two Sum II
- leetcode01. Two SumII
- LeetCode167.Two Sum II
- LeetCode167. Two Sum II
- LeetCode167. Two Sum II
- leetcode167
- leetcode167
- Leetcode167 - Two Sum II - Input array is sorted(two pointers)
- [LeetCode167]Two Sum II - Input array is sorted
- leetcode167. Two Sum II - Input array is sorted
- LeetCode167—Two Sum II - Input array is sorted
- Leetcode167. Two Sum II - Input array is sorted
- BigDecimal的精确计算
- [LeetCode] 136. Single Number java
- sklearn-数据预处理
- 关于 Android 适配,看完这篇文章就够了
- XP和WIN10环境变量比较
- leetcode167 Two SumII java
- 读源码1
- [LeetCode] 137. Single Number II java
- Android系统启动流程概述
- 串口终端xmodem烧录linux内核linux uboot的方法
- Android VPN source code
- Python 机器(算法)学习-----第一天
- 大数据平台CDH集群离线搭建
- php读取文件内容的五种方式