Leetcode : Two Sum 2
- Programming/알고리즘
- 2020. 3. 29. 14:43
167. Two Sum 2 - Input array is sorted
- 난이도 : Easy
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.
코드구현
class Solution {
public int[] twoSum(int[] numbers, int target) {
int[] answer = {0,0};
for(int i=0;i<numbers.length;i++){
for(int j=i+1;j<numbers.length;j++){
int sum = numbers[i]+numbers[j];
if (sum == target){
answer[0] = i+1;
answer[1] = j+1;
break;
}
}
}
return answer;
}
}
요약
- 이중 포문을 이용하여, target이 되는 값을 찾는다.
- j=i+1 부터 연산하여, 중복연산이 일어나는 경우를 막는다.
문제
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
'Programming > 알고리즘' 카테고리의 다른 글
[Leetcode] Split Array Largest Sum (0) | 2020.03.29 |
---|---|
[Programmers] 완주하지 못한 선수 (0) | 2020.03.21 |