LeetCode 풀기 - 167. Two Sum II

백지우·2026년 8월 26일

LeetCode

목록 보기
5/76
  • LeetCode 최소 하루에 하나는 풀자는 마인드
  • 사용언어: JAVA

167. Two Sum II

첫번째 풀이

  • 방법: 마찬가지로 Two Pointer사용. 정해진 target값을 맞추기 위하여 left + right 값 한 뒤, target보다 작으면 left++, 크면 right--했음
class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int left = 0;
        int right = numbers.length - 1;

        while(left < right){
            int sum = numbers[left] + numbers[right];
            if(sum == target) {
                return new int[]{left+1, right+1};
            }
            else if (sum < target){
                left++;
            }
            else{
                right--;
            }
        }

        return new int[]{};
    }
}

  • 코드 작성하다가 느낀점
    - 시간복잡도 O(n) 공간복잡도 O(1)
    • 문제 제대로 안읽어서 1-indexed인줄 몰랐음. 한번 돌려보고 수정됨

0개의 댓글