网站怎么做飘窗,网站seo策划方案案例分析,一个网站上线的时间,网站上传不了图片是什么原因题目描述 数组中有一个数字出现的次数超过数组长度的一半#xff0c;请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次#xff0c;超过数组长度的一半#xff0c;因此输出2。分析#xff1a;找数组中出现次数超过一半的数字请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次超过数组长度的一半因此输出2。 分析找数组中出现次数超过一半的数字我们一半可以采用两种方法一是使用快排对数组进行排序然后直接输出排序数组中间位置的数。第二种是使用HashMapInteger,Integer,key是数组中的数字value为其在数组中出现的次数顺序扫描数组记录下数组出现的次数输出大于数组长度一半的value值对应的key值。 第一种方法代码很简单此处不表第二种方法的代码如下 1 import java.util.ArrayList;2 import java.util.Arrays;3 import java.util.Collection;4 import java.util.HashMap;5 import java.util.Set;6 7 public class Solution {8 public int MoreThanHalfNum_Solution(int [] array) {9 if(arraynull||array.length0){
10 return 0 ;
11 }
12 if(array.length1){
13 return array[0] ;
14 }
15 int most0 ;
16 HashMapInteger,Integer m new HashMapInteger,Integer() ;
17 for(int i 0 ; i array.length ;i){
18 if(!m.containsKey(array[i])){
19 m.put(array[i], 1) ;
20 }
21 else{
22 int temp m.get(array[i]);
23 m.put(array[i], temp1) ;
24 }
25
26 }
27 SetInteger a m.keySet() ;
28 for(int temp : a){
29 if(m.get(temp)(array.length/2)){
30 most temp ;
31 }
32 }
33 return most ;
34 }
35 } 转载于:https://www.cnblogs.com/huntertoung/p/4803147.html