[LeetCode] Two Sum

아르당·2024년 11월 13일

LeetCode

목록 보기
1/68
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

정수의 배열 nums와 정수 target이 주어지고, 두 수의 합이 target이 되는 인덱스를 반환해라.
정확히 하나의 답이 있으며, 동일한 요소는 두 번 사용할 수 없다.
답을 어떤 순서로든 반환할 수 있다.

Examlple

#1
Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1]
Explanation: Because nums[0] + nums[1] == 9, [0, 1]을 반환한다.

#2
Input: nums = [3, 2, 4], target = 6
Output: [1, 2]

#3
input: nums = [3, 3], target = 6
Output: [0, 1]

Constraints

  • 2 <= nums.length <= 10^4
  • -10^9 <= nums[i] <= 10^9
  • -10^9 <= target <= 10^9
  • 오직 하나의 답만 존재한다.

Solved

여러가지 방법이 있지만 Two Pointer 방법으로 문제를 풀어보았다.

정수 left와 right를 선언해주고 left에는 0, right에는 left + 1을 할당한다.

int left = 0;
int right = left + 1;

그리고 while문을 통해 반복해주는데 이때 target을 구할때까지 while문이 동작할 수 있게 조건을 넣어준다.

while(left < right){

}

nums[left]와 nums[right] 합이 target과 같다면 while문을 빠져나오게 한다. 계속 반복하면서 right를 증가시켜주고, right가 nums의 길이와 같거나 커지면 left를 증가시켜주고 right에 left + 1을 할당한다.

while(left < right){
  if(nums[left] + nums[right] == target){
    break;
  }
  
  right;
  
  if(right >= nums.length){
    left++;
    right = left + 1;
  }
}

크기가 2인 int 배열 result를 생성하고, 0번째에 left, 1번째에 right를 할당하고 result를 반환한다.

int[] result = new int[2];
result[0] = left;
result[1] = right;

return result;

All Code

public int[] twoSum(int[] nums, int target){
  int left = 0;
  int right = left + 1;

  while(left < right){
    if(nums[left] + nums[right] == target){
      break;
    }

    right++;

    if(right >= nums.length){
      left++;
      right = left + 1;
    }
  }

  int[] result = new int[2];
  result[0] = left;
  result[1] = right;

  return result;
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글