首页 > 试题广场 >

在数组中找到出现次数大于一半的数

[编程题]在数组中找到出现次数大于一半的数
  • 热度指数:1800 时间限制:C/C++ 2秒,其他语言4秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定一个整型数组arr,请打印其中出现次数大于一半的数,如果没有这样的数,请输出-1。

输入描述:
输入包含两行,第一行包含一个整数n,代表数组长度,第二行包含n个数,代表数组arr


输出描述:
输出一个整数,代表出现次数大于一半的数,如果没有这样的数,请输出‘-1“。
示例1

输入

5
11 7 5 7 7

输出

7
示例2

输入

4
2 2 3 3

输出

-1

备注:
时间复杂度,额外空间复杂度
如果有这样的数存在,它一定是排完序后在中间的数,我们可以遍历一下数组再检查一下是不是出现次数大于数组长度的一半,以确保不输出-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),可以用基于桶排序思想的排序方法。
发表于 2021-11-14 09:03:24 回复(0)
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");
        }
        
		
	}
}



发表于 2019-10-24 11:10:39 回复(0)