输入包含两行,第一行包含一个整数n,代表数组长度,第二行包含n个数,代表数组arr
。
输出一个整数,代表出现次数大于一半的数,如果没有这样的数,请输出‘-1“。
5 11 7 5 7 7
7
4 2 2 3 3
-1
时间复杂度,额外空间复杂度
。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String[] params = br.readLine().split(" ");
int[] arr = new int[n];
for(int i = 0; i < n; i++) arr[i] = Integer.parseInt(params[i]);
Arrays.sort(arr);
int target = arr[arr.length / 2], count = 0;
for(int num: arr) if(num == target) count ++;
System.out.println(count > arr.length / 2? target: -1);
}
} 要想时间复杂度达到O(n),可以用基于桶排序思想的排序方法。 def max_count(arr):
count = {}
for i in set(arr):
count[i] = arr.count(i)
return count
num = input()
arr = input().split()
map = max_count(arr)
l = sorted(map.items(),key = lambda x:x[1])
if l[-1][-1] > len(arr)/2:
print(l[-1][0])
else:
print(-1) import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] arr = new int[n];
for(int i=0;i<n;i++){
arr[i] = scanner.nextInt();
}
int times = 0;
int cand = 0;
for(int i=0;i<n;i++){
if(times==0){
cand = arr[i];
times++;
}else if(arr[i] == cand){
times++;
}else{
times--;
}
}
times = 0;
for(int i=0;i<n;i++){
if(arr[i] == cand){
times++;
}
}
if(times > n/2){
System.out.print(cand);
}else{
System.out.print("-1");
}
}
}
#include<iostream>
#include<map>
using namespace std;
int main()
{
int n;
while (cin >> n)
{
int temp=0;
map<int, int>v;
v.clear();
for (int i = 0; i < n; i++)
{
cin >> temp;
v[temp]++;
}
int k = n / 2;
for(auto ptr=v.begin();ptr!=v.end();ptr++)
{
if(ptr->second>k)
{
cout<<ptr->first<<endl;
return 0;
}
}
cout<<"-1"<<endl;
}
return 0;
} 这个题用map做觉得很合适,正常读取数据放入map之中,同步更新key对应的value值,而后再进行一次遍历,通过value值找key,找到就是有,找不到就是没有,只需要遍历一次即可