LeetCode之Two Sum II - Input array is sorted

简介: LeetCode之Two Sum II - Input array is sorted

1、题目


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


Subscribe to see which companies asked this question.


2、代码实现

public class Solution {

   public int[] twoSum(int[] nums, int target) {

       if (null == nums)  

           return null;        

       int[] result = new int[2];  

       HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();  

       for (int i = 0; i < nums.length; ++i) {  

           Integer value = map.get(nums[i]);  

           if (null == value)  

               map.put(nums[i], i);  

           Integer index = map.get(target - nums[i]);  

           if (null != index && index < i)  

           {  

               result[0] = index + 1;  

               result[1] = i + 1;  

           }  

       }  

       return result;  

   }

}


相关文章
|
存储 缓存 算法
LeetCode刷题---Two Sum(一)
LeetCode刷题---Two Sum(一)
|
存储 算法 安全
LeetCode - #2 Add Two Numbers
我们社区从本期开始会将顾毅(Netflix 增长黑客,《iOS 面试之道》作者,ACE 职业健身教练。)的 Swift 算法题题解整理为文字版以方便大家学习与阅读。 不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。
233 0
LeetCode - #2 Add Two Numbers
|
存储 算法 安全
LeetCode - #1 Two Sum
我们社区从本期开始会将顾毅(Netflix 增长黑客,《iOS 面试之道》作者,ACE 职业健身教练。)的 Swift 算法题题解整理为文字版以方便大家学习与阅读。 不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。
118 0
LeetCode - #1 Two Sum
Leetcode 4. Median of Two Sorted Arrays
题目描述很简单,就是找到两个有序数组合并后的中位数,要求时间复杂度O(log (m+n))。 如果不要去时间复杂度,很容易就想到了归并排序,归并排序的时间复杂度是O(m+n),空间复杂度也是O(m+n),不满足题目要求,其实我开始也不知道怎么做,后来看了别人的博客才知道有个二分法求两个有序数组中第k大数的方法。
154 0
Leetcode Find Minimum in Rotated Sorted Array 题解
对一个有序数组翻转, 就是随机取前K个数,移动到数组的后面,然后让你找出最小的那个数,注意,K有可能是0,也就是没有翻转。
158 0
|
存储 C++ Python
LeetCode刷题---Add Two Numbers(一)
LeetCode刷题---Add Two Numbers(一)
Search in Rotated Sorted Array - 循环有序数组查找问题
Search in Rotated Sorted Array - 循环有序数组查找问题
184 0
LeetCode 167 Two Sum II - Input array is sorted(输入已排序数组,求其中两个数的和等于给定的数)
给定一个有序数组和一个目标值 找出数组中两个成员,两者之和为目标值,并顺序输出
179 0
|
8月前
|
测试技术 PHP 开发者
PHP 数组查找:为什么 `isset()` 比 `in_array()` 快得多?
PHP 数组查找:为什么 `isset()` 比 `in_array()` 快得多?
|
12月前
|
人工智能 Java
Java 中数组Array和列表List的转换
本文介绍了数组与列表之间的相互转换方法,主要包括三部分:1)使用`Collections.addAll()`方法将数组转为列表,适用于引用类型,效率较高;2)通过`new ArrayList&lt;&gt;()`构造器结合`Arrays.asList()`实现类似功能;3)利用JDK8的`Stream`流式计算,支持基本数据类型数组的转换。此外,还详细讲解了列表转数组的方法,如借助`Stream`实现不同类型数组间的转换,并附带代码示例与执行结果,帮助读者深入理解两种数据结构的互转技巧。
874 1
Java 中数组Array和列表List的转换