carloscn / structstudy

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

leetcode1287:有序数组中出现次数超过25%的元素(element-appearing-more-than-25-in-sorted-array) #201

Open carloscn opened 1 year ago

carloscn commented 1 year ago

问题描述

给你一个非递减的 有序 整数数组,已知这个数组中恰好有一个整数,它的出现次数超过数组元素总数的 25%。

请你找到并返回这个整数

示例:

输入:arr = [1,2,2,6,6,6,6,7,10] 输出:6  

提示:

1 <= arr.length <= 10^4 0 <= arr[i] <= 10^5

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/element-appearing-more-than-25-in-sorted-array

carloscn commented 1 year ago

问题分析

遍历数组,记录一个count,如果和下一个相等就+,+完判断是否超过20%,是就返回,不是就继续。

pub fn find_special_integer(arr: Vec<i32>) -> i32
{
    if arr.len() < 1 {
        return 0;
    }
    let mut count = 0;

    for i in 0..arr.len() - 1 {
        if arr[i] == arr[i + 1] {
            count += 1;
            if count as f64 / arr.len() as f64 >= 0.25_f64 {
                return arr[i];
            }
        } else {
            count = 0;
        }
    }

    return 0;
}
carloscn commented 1 year ago

code

https://review.gerrithub.io/c/carloscn/structstudy/+/553202 https://github.com/carloscn/structstudy/commit/f404aa4791817641be2da891fdd9ca932c81c912