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;
    }
}
(0)

相关推荐

  • 剑指offer

    03 数组中重复的数字 public int findRepeatNumber(int[] nums){ //排序后的数组,重复元素必然相邻 Arrays.sort(nums); //结果集 int ...

  • 【LeetCode】347. Top K Frequent Elements 前 K 个高频元素(Medium)(JAVA)

    [LeetCode]347. Top K Frequent Elements 前 K 个高频元素(Medium)(JAVA) 题目地址: https://leetcode.com/problems/t ...

  • (1条消息) 两数之和,程序员才懂的 TwoSum 和 Abandon !

    (1条消息) 两数之和,程序员才懂的 TwoSum 和 Abandon !

  • leetcode之Two Sum

    The function twoSum should return indices of the two numbers such that they add up to the target, wh ...

  • LeetCode之Reverse String II

    LeetCode之Reverse String II

  • LeetCode之Remove Duplicates from Sorted Array II

    LeetCode之Remove Duplicates from Sorted Array II

  • ​LeetCode刷题实战264:丑数 II

    算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试.所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 ! 今天和大家 ...

  • ​LeetCode刷题实战253:会议室II

    算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试.所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 ! 今天和大家 ...

  • ​LeetCode刷题实战267:回文排列II

    算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试.所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 ! 今天和大家 ...

  • ​LeetCode刷题实战244:最短单词距离 II

    算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试.所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 ! 今天和大家 ...

  • ​LeetCode刷题实战227:基本计算器 II

    算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试.所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 ! 今天和大家 ...

  • ​LeetCode刷题实战219:存在重复元素 II

    算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试.所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 ! 今天和大家 ...