[알고리즘] LeetCode - Two Sum II - Input Array Is Sorted

2023. 8. 28. 02:17·알고리즘/leet code
 

Two Sum II - Input Array Is Sorted - LeetCode

Can you solve this real interview question? Two Sum II - Input Array Is Sorted - Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two n

leetcode.com

문제 설명

  • 정수형 배열 numbers가 오름차순 정렬되어 주어진다.
  • 두 숫자의 합인 정수형 변수 target이 주어진다.
  • numbers에서의 두 수의 합이 target이 되는 두 개의 인덱스를 포함한 정수형 배열을 반환한다.
  • target값을 만들 수 있는 두 수가 있는 경우는 하나 이상 주어진다.

문제 해결

  • 두 개의 포인터(투포인터)를 통해 양쪽에서 접근한다.
  • 포인터로 지목된 두 수의 합이 target보다 크면 뒤쪽 포인터를 하나 줄이고, target보다 작으면 앞쪽 포인터를 하나 늘린다.
  • 두 수의 합이 target과 일치할 때 또는 앞 포인터가 뒤 포인터보다 작을 때까지 반복한다.

시간 복잡도

  • O(N)
  • 정수형 배열 numbers의 크기만큼만 반복하면 되기 때문에 시간 복잡도는 O(N)이다.

유사 코드

앞 포인터 head 선언 후 0으로 초기화
뒤 포인터 tail 선언 후 (numbers길이 - 1)으로 초기화

앞 포인터가 뒤 포인터보다 작을 때까지 반복
	sum = head위치의 값과 tail위치의 값의 합
	sum과 target이 같으면
    	반복문 중지
	sum이 target보다 크면
    	tail--
    sum이 target보다 작으면
    	head++
return [head + 1, tail + 1] 정수형 배열 반환

풀이 코드

class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int head = 0;
        int tail = numbers.length - 1;

        while(head < tail) {
            int sum = numbers[head] + numbers[tail];

            if (sum == target) {
                break;
            } else if (sum > target) {
                tail--;
            } else if (sum < target) {
                head++;
            }
        }

        return new int[]{head + 1, tail + 1};
    }
}

결과

시간 메모리
2 ms 45.3 MB

'알고리즘 > leet code' 카테고리의 다른 글

[알고리즘] LeetCode - Longest Substring Without Repeating Characters  (0) 2023.08.28
[알고리즘] LeetCode - Minimum Size Subarray Sum  (0) 2023.08.28
[알고리즘] LeetCode - Valid Palindrome  (0) 2023.08.28
[알고리즘] LeetCode - Jump Game  (0) 2023.08.25
[알고리즘] LeetCode - Best Time to Buy and Sell Stock II  (0) 2023.08.25
'알고리즘/leet code' 카테고리의 다른 글
  • [알고리즘] LeetCode - Longest Substring Without Repeating Characters
  • [알고리즘] LeetCode - Minimum Size Subarray Sum
  • [알고리즘] LeetCode - Valid Palindrome
  • [알고리즘] LeetCode - Jump Game
tableMinPark
tableMinPark
Backend Engineer
  • tableMinPark
    Sangmin's Tech Blog
    tableMinPark
  • 전체
    오늘
    어제
  • 블로그 메뉴

    • tech study blog
    • my github
    • monglife github
    • 분류 전체보기 (48)
      • 개발 (7)
        • java (0)
        • kotlin (0)
        • spring boot (0)
        • android (0)
        • junit5 (5)
        • architecture (2)
      • 데브옵스 (3)
        • docker (3)
        • github action (0)
        • grafana (0)
        • prometheus (0)
        • elk (0)
      • 알고리즘 (35)
        • baek joon (0)
        • programmers (4)
        • leet code (29)
      • 일상 (3)
        • Wear OS 앱 개발기 (2)
        • 회고 (1)
  • 태그

    bind mount
    apple watch
    Thread
    micro service
    wear os
    MVVM
    docker network
    synchronized
    volume
    Galaxy watch
    java
    20.04
    Kotlin
    Android
    레이어드 아키텍처
    layered architecture
    mongs
    MSA
    docker compose
    docker-compose
    docker
    ubuntu
    jetpack-compose
    monglife
    Container
  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
tableMinPark
[알고리즘] LeetCode - Two Sum II - Input Array Is Sorted
상단으로

티스토리툴바