LeetCode(二)투썸의 실현에 관하여
정수를 정하고 그 안에서 두 개의 수를 찾아내면 그 합은 지정된 정수와 같다.
프로그램은 이 두 개의 수가 수조에 있는 위치를 되돌려줍니다. (수조 아래 표시는 1에서 시작합니다.) 그리고 위치가 작은 것은 앞에 있습니다.
예를 들어, 배열 {2, 7, 11, 15}, 정수 = 9 지정
반환: {1,2}
Given an array of integers, 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. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
문제 해결 방법:
1) 하나의 그룹을 복제하고 복제된 그룹을 작은 그룹에서 큰 그룹으로 정렬한다.
2) 정렬 후 배열의 첫 번째 수를 첫 번째 수로 지정하고 마지막 수를 두 번째 수로 지정하면 첫 번째 수는 배열에서 가장 작은 수이고 두 번째 수는 배열에서 가장 큰 수임을 알 수 있다.
3) 두 수의 합(sum)과 지정한 정수(target)의 크기를 비교한다. 만약sum가 target보다 작으면 두 번째 수가 가장 큰 수이기 때문에 첫 번째 수가 너무 작기 때문에 첫 번째 수가 앞으로 이동한다.반대로 만약sum가 target보다 크면 첫 번째 수가 이미 가장 작은 수이기 때문에 두 번째 수가 너무 크기 때문에 두 번째 수는 뒤로 옮겨야 한다.
4) 두 개의 수가 지나면sum가 지정한 정수 target과 꼭 같을 때까지 세 번째 단계를 반복한다.
5) 이 두 개의 수가 원래 수조에 있는 위치를 찾아 아래 표로 되돌아간다.
코드:
public static int[] twoSum(int[] numbers, int target) {
int[] result = new int[]{-1,-1};
int len = numbers.length;
int[] sortedNumbers = new int[len];
System.arraycopy(numbers, 0, sortedNumbers, 0, len);
int first = 0;
int second = len - 1;
Arrays.sort(sortedNumbers);
while(first < second){
if(sortedNumbers[first] + sortedNumbers[second] < target){
first++;
continue;
}
if(sortedNumbers[first] + sortedNumbers[second] > target){
second--;
continue;
}
break;
}
int n1 = sortedNumbers[first];
int n2 = sortedNumbers[second];
for (int i = 0; i < len; i++) {
if (n1 == numbers[i] || n2 == numbers[i]) {
if (result[0] == -1) {
result[0] = i + 1;
} else {
result[1] = i + 1;
break;
}
}
}
return result;
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
python 문자열 입력으로 모든 유효한 IP 주소 생성(LeetCode 93번 문제)이 문제의 공식 난이도는 Medium으로 좋아요 1296, 반대 505, 통과율 35.4%를 눌렀다.각 항목의 지표로 말하자면 보기에는 약간 규범에 맞는 것 같지만, 실제로도 확실히 그렇다.이 문제의 해법과 의도는 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.