carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode2148: Count Elements With Strictly Smaller and Greater Elements #347

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

Given an integer array nums, return the number of elements that have both a strictly smaller and a strictly greater element appear in nums.

Example 1:

Input: nums = [11,7,2,15] Output: 2 Explanation: The element 7 has the element 2 strictly smaller than it and the element 11 strictly greater than it. Element 11 has element 7 strictly smaller than it and element 15 strictly greater than it. In total there are 2 elements having both a strictly smaller and a strictly greater element appear in nums.

Example 2:

Input: nums = [-3,3,3,90] Output: 2 Explanation: The element 3 has the element -3 strictly smaller than it and the element 90 strictly greater than it. Since there are two elements with the value 3, in total there are 2 elements having both a strictly smaller and a strictly greater element appear in nums.

Constraints:

1 <= nums.length <= 100 -105 <= nums[i] <= 105

carloscn commented 1 year ago

Analysis

pub fn count_elements(nums: Vec<i32>) -> i32
{
    let mut ret:i32 = 0;

    if nums.len() < 1 {
        return ret;
    }
    let mut max_val:i32 = i32::MIN;
    let mut min_val:i32 = i32::MAX;

    for i in 0..nums.len() {
        max_val = max_val.max(nums[i]);
        min_val = min_val.min(nums[i]);
    }

    for i in 0..nums.len() {
        if nums[i] > min_val && nums[i] < max_val {
            ret += 1;
        }
    }

    return ret;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1168960 https://github.com/carloscn/structstudy/commit/50096605d5311d2eb38b4a1a39675192404fb842