LeetCode(二)투썸의 실현에 관하여

2025 단어 LeetCodeTwoSum
제목:
정수를 정하고 그 안에서 두 개의 수를 찾아내면 그 합은 지정된 정수와 같다.
프로그램은 이 두 개의 수가 수조에 있는 위치를 되돌려줍니다. (수조 아래 표시는 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;
	}

좋은 웹페이지 즐겨찾기