Leetcode - path-sum
Leetcode - surrounded-regions

Leetcode - how-many-numbers-are-smaller-than-the-current-number

violet posted @ Mar 10, 2020 07:37:16 AM in 算法 with tags Algorithm array ruby count sort , 670 阅读

https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/

Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i].

Return the answer in an array.

 

Example 1:

Input: nums = [8,1,2,2,3]
Output: [4,0,1,1,3]
Explanation: 
For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3). 
For nums[1]=1 does not exist any smaller number than it.
For nums[2]=2 there exist one smaller number than it (1). 
For nums[3]=2 there exist one smaller number than it (1). 
For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).

Constraints:

  • 2 <= nums.length <= 500
  • 0 <= nums[i] <= 100

This is a count sort problem actually. It already provides the number range is from 0 to 100. So just creating two arrays, pre_count and count, with 101 length to store all the numbers, index is number, value is count. And then modify count from 1 to 101, sum count from the previous one for each point. And then iterate the numbers and store count[val] - pre_count[val]

# @param {Integer[]} nums
# @return {Integer[]}
def smaller_numbers_than_current(nums)
    count = Array.new(101, 0)
    pre_count = Array.new(101, 0)
    nums.each do |val|
        count[val] += 1
        pre_count[val] += 1
    end
    i = 1
    while i < 101
      count[i] = count[i] + count[i-1]
      i += 1
    end
  
    result = []
    nums.each do |val|     
        result << count[val] - pre_count[val]
    end
    
    return result
end

 


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter