LeetCode之Two Sum II - Input array is sorted
发布日期:2021-06-29 14:08:18 浏览次数:2 分类:技术文章

本文共 1228 字,大约阅读时间需要 4 分钟。

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

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
map = new HashMap
(); 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; }}

 

 

 

 

 

转载地址:https://chenyu.blog.csdn.net/article/details/69810329 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Android之解决360奇酷手机控制台打印全等级日志(默认只打印W、E等级日志)
下一篇:LeetCode之Power of Two

发表评论

最新留言

初次前来,多多关照!
[***.217.46.12]2024年05月01日 12时43分53秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章