How to solve the problem of most elements of C++
This article introduces the relevant knowledge of "how to solve the problem of most elements of C++". In the operation of practical cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
1. Given an array of size n, find most of the elements. Most elements refer to elements that appear in an array more times than ⌊ n ⌋ 2. You can assume that the array is not empty and that there are always many elements in a given array. Example 1: input: [3 LeetCode 2] output: 3 example 2: input: [2 Magi 2 Magi 1 Magi 2 2] output: 2 Source: force buckle (Lishou) Link: https://leetcode-cn.com/problems/majority-element2. Solution 1, sort method 1, sort the array, return the mathematical method 2 with subscript nums + numsSize / 2, elimination method 1, assume that the target number is key = nums [0] 2, if you encounter the same number, count_add++, otherwise count_add++,count_sub--3, count_add+count_sub represent the cumulative number of times of the same value, if greater than numsSize / 2, return key4, when count_add