averagePair 문제풀이

이후띵·2022년 4월 5일
0

알고리즘

목록 보기
13/14

내 풀이

/*
 문제
	Write a function called averagePair.
	Given a sorted array of integers and
	a target average, determine if there is
	a pair of values in the array where the
	average of the pair equals the target average.
	There may be more than one pair that matches the
	average target.

	Bonus Constraints:
		Time: O(N)
		Space: O(1)
 */

function averagePair(arr, n) {
    let num = 2 * n;
    if (!Number.isInteger(num) || !arr.length) {
        return false;
    }
    let start = 0;
    let end = arr.length - 1;
    while (start < end) {
        let tmp = arr[start] + arr[end];
        if (num === tmp) {
            return true;
        } else if (tmp < num) {
            start++;
        } else {
            end--;
        }
    }
    return false;
}

console.log(averagePair([1, 2, 3], 2.5)); // true
console.log(averagePair([1, 3, 3, 4, 6, 7, 10, 12, 17, 19], 8)); // true
console.log(averagePair([-1, 0, 3, 5, 6, 7], 4.1)); // false
console.log(averagePair([], 4)); // false

간단 설명

  • 투 포인터로 해결
  • while문 돌면서 크기 비교후 start, end값 결정
  • 다돌았는데 return 안됐을 때 false return
  • 시간복잡도: O(N)
  • 공간복잡도: O(1)
profile
이후띵's 개발일지

0개의 댓글