LeetCode 167 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.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

Difficulty
Easy

Analysis

For a sorted array, the best way is to use two-indexers method

Idea
Use two indexers to find the target

Solutions
  1. Cpp solution 6ms
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        if(nums.size() < 2) return {};
        int begin = 0, end = (int)(nums.size() - 1);
        while(begin < end) {
            int sum = nums[begin] + nums[end];
            if(sum == target) {
                return {begin+1, end+1};
            } else if (sum < target){
                begin++;
            } else {
                end--;
            }
        }
        return {};
    }
};
  1. Go solution 9ms
func twoSum(nums []int, target int) []int {
    begin, end := 0, len(nums) - 1
    for begin < end {
        sum := nums[begin] + nums[end]
        if sum == target {
            return append([]int(nil), begin+1, end+1)
        } else if sum < target {
            begin++
        } else {
            end--
        }
    }
    return nil
}
Reference

results matching ""

    No results matching ""