ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Two Sum II - Input array is sorted
    알고리즘 2019. 7. 29. 16:23

    LeetCode 167번

    Tags. array, binary Search, Two Pointers

     

    https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/

     

    Two Sum II - Input array is sorted - LeetCode

    Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

    leetcode.com

     

    문제

    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.

    Note:

    • 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.

    Example:

    Input: numbers = [2,7,11,15], target = 9

    Output: [1,2]

    Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.

     

    Solution

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    class Solution {
        public int[] twoSum(int[] numbers, int target) {
            int[] result = new int[2];
            int upperBound = numbers.length - 1;
            int lowerBound = 0;
            
            while(lowerBound <= upperBound) {
                
                
                if(target == numbers[lowerBound] + numbers[upperBound]) {
                    result[0= lowerBound + 1;
                    result[1= upperBound + 1;
                    return result;
                    
                }else if(numbers[lowerBound] + numbers[upperBound] > target) {
                    upperBound--;
                }else {
                    lowerBound ++;
                }
            }
            return result;
        }
    }
    cs

    고찰

    문제를 해석하자면 파라미터로 들어오는 numbers의 배열의 원소 조합으로 파라미터 target을 만들 수 있는 원소의 인덱스값 (1부터 시작) 을 배열로 반환하는 문제이다.

    풀이 방법으로는

    1. 결과를 반환할 배열을 만든다 

    2. numbers의 맨처음 인덱스(lowerBound)와 마지막 인덱스(upperBound)를 변수로 만든다.

    3. lowerBound와 upperBound의 값이 같아질때까지 실행되는 반복문 조건을 주고

    4. 배열의 각 인덱스에 위치해 있는 값을 더해서 target과 비교했을 때

    5. 값이 같을때 결과 값에 인덱스 값을 1씩 더해서 넣고

    6. target값이 작으면 upperBound 위치를 -1 해주고

    7. target값이 크면 lowerBound 위치를 +1 더해주는 방식으로 

    구현하였다.

     

    Runtime : 1ms

    Memory : 38.3MB

    '알고리즘' 카테고리의 다른 글

    Next Greater Element I  (0) 2019.07.29
    Backspace String Compare  (0) 2019.07.29
    Peak Index in a Mountain Array  (0) 2019.07.29
    Intersection of Two Arrays  (0) 2019.07.29
    Binary Search  (0) 2019.07.23
Designed by Tistory.