LeetCode - 2824. Count Pairs Whose Sum is Less than Target

henu·2023년 8월 31일
0

LeetCode

목록 보기
30/186
post-thumbnail

Solution

var countPairs = function(nums, target) {
    let count = 0;

    for(let i=0; i<nums.length; i++) {
        for(let j=i+1; j<nums.length; j++) {
            if(nums[i] + nums[j] < target) count++;
        }
    }

    return count;
};

Explanation

이중 for문을 이용해서 해결했다.

  • 0 <= i < j < n
  • nums[i] + nums[j] < target
    위의 두 조건을 만족해야한다.
    첫 번째 for문을 이용해 요소에 접근한다.
    그리고 두 번째 for문의 초기식(let j=i+1)를 통해 첫 번째 조건을 자연스럽게 만족하게된다.
    그리고 두 번째 조건이 만족할 경우 count를 1씩 증가시킨다.

0개의 댓글