Two Sum II - Input array is sorted

题目

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

解析

这个题是two sum的变种,返回符合题意 two integers 的位置(从自然数1开始数)

思路

  1. just need change from return new int []{i,v} to return new int []{i+1,v+1}

图解

代码

class Solution {
    public int[] twoSum(int[] nums, int target) {
      HashMap<Integer, Integer> map = new HashMap<>();
      for(int i = 0; i< nums.length; i++){
          map.put(nums[i],i);
      }

      for(int i = 0; i< nums.length; i++){
          Integer v = map.get(target - nums[i]);
          if(v!= null && v>i){
              return new int []{i+1,v+1};
          }
      }     
      return null;
    }
}

results matching ""

    No results matching ""