LeetCode 02 Sum of Two Numbers II - Input Sorted Array

topic:

Given a sorted array sorted in ascending order  , find two numbers such that their sum is equal to the target number.

The function should return the two subscript values ​​index1 and index2, where index1 must be less than index2 .

illustrate:

  • The returned subscript values ​​(index1 and index2) are not zero-based.
  • You can assume that each input corresponds to a unique answer, and you can't reuse the same elements.

Example:

Input: numbers = [2, 7, 11, 15], target = 9
 Output: [1,2]
 Explanation: The sum of 2 and 7 is equal to the target number 9. So index1 = 1, index2 = 2 .

Idea: Because it is an ordered array, move towards the middle from the beginning value left and end value right of the incoming array. If the sum is greater than target, then right--, otherwise, left++, until the sum equals target, the time complexity is O( n)

code show as below:

public static int[] TwoSum(int[] numbers, int target)
        {
            int[] result = new int[2];
            int left = 0, right = numbers.Length - 1;
            while (left < right)
            {
                int temp = numbers[left] + numbers[right];
                if (temp == target)
                {
                    result[0] = left + 1;
                    result[1] = right + 1;
                    break;
                }
                if (temp > target)
                    right--;
                else
                    left++;
            }
            return result;
        }

Main method:

static void Main(string[] args)
        {
            int[] numbers = new int[] { 2, 7, 11, 15 };
            int[] result = TwoSum(numbers, 9);
            for(int i=0;i<result.Length;i++)
            {
                Console.Write(result[i] + " ");
            }
            Console.ReadKey();
        }
Summary: This is a derivative of the sum of two numbers. The method of the sum of two numbers can also be used here, but because it provides an ordered array, this method looks more concise. I read it online and basically All use this method, if you have other methods, welcome to communicate with me.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326659679&siteId=291194637