Skip to content
Snippets Groups Projects

Two Sum II - Input Array Is Sorted

  • Clone with SSH
  • Clone with HTTPS
  • Embed
  • Share
    The snippet can be accessed without any authentication.
    Authored by Kiryuu Sakuya
    Program.cs 855 B
    using System;
    using System.Collections.Generic;
    
    namespace test
    {
        class Program
        {
            public static int[] TwoSum(int[] numbers, int target)
            {
                if (numbers.Length == 2)
                {
                    return new int[]{1, 2};
                }
    
                int min = 0, max = numbers.Length - 1, temp = 0;
                while (numbers[min] + numbers[max] != target)
                {
                    if ((numbers[min] + numbers[max]) > target)
                        max--;
                    else
                        min++;
                }           
                return new int[]{min + 1, max + 1};
            }
            public static void Main(string[] args)
            {
                int[] a = { 2, 7, 11, 15 };
                int b = 9;
                int[] c = TwoSum(a, b);
                Console.WriteLine("[{0}]", string.Join(", ", c));
            }
        }
    }
    0% Loading or .
    You are about to add 0 people to the discussion. Proceed with caution.
    Finish editing this message first!
    Please register or to comment