Two Sum 문제 (leetcode 167)
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.
작은 수에서 큰수로 정렬된 배열을 주고 그 배열 내에서 두개의 값을 더 할 경우 대상의 값과 똑같을씨 그 두 개의 값의 인덱스를 리턴해야 하는 문제이다.
주의 : 인덱스들중 0은 없다 (인덱스는 1부터 시작한다)
각각의 인풋마다 하나의 답만 있고 같은 인덱스 값을 두번 쓸수는 없다.
1
2
3
4
5
6
7
8
9
10
11
12
|
class Solution {
public int[] twoSum(int[] numbers, int target) {
//맨끝쪽
int right = numbers.length-1;
//처음
int left = 0;
//처음 기준이 맨 끝쪽을 넘어설때까지 반복문을 돌림
while (left<right) {
//처음 값과 끝값을 더했을때 대상의 값과 똒같다면 처음 값과 끝값의 인덱스를 넘겨줌 1을 더하는 이유는 주의사항에 인덱스는 1부터 시작 한다고 적혀있음
if (numbers[left]+numbers[right]==target) return new int[] {left+1, right+1};
//두개의 값의 합이 대상의 값보다 크면은 끝값을 1줄여줌 왜냐하면 배열은 정렬된 상태이고 맨 끝값이 제일 큰수 인 상태이기때문
else if (numbers[left]+numbers[right]>target) right--;
//두개의 값의 합이 대상의 값보다 크면은 처음 값을 1늘려줌
else left++;
}
return new int[] {};
}
}
|
cs |