比较排序汇总

一、比谁的因子数多

两组数个数都为n,第一组数可以随便换顺序,依次和第二组数作比较,比较规则是因子数多的数获胜,每个数只能用一次,求第一组获胜的最大次数

求一个数的因子,leecode1492,比如 8 的因子为(1,2,4,8) 

https://leetcode-cn.com/problems/the-kth-factor-of-n/solution/n-de-di-k-ge-yin-zi-by-leetcode-solution/

例子:3(n)

1 3 5   (因子数 1 2 2)

4 2 6   (因子数 3 2 4)

输出 0 (怎么换顺序都赢不了)

输入 3

5 8 9

4 12 6

输出 1

输入 3

1 1 2

1 1 2

输出 1

package zsh;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;

public class Tencent2 {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int[] arr1 = new int[n];
        Integer[] arr11 = new Integer[n];
        int[] arr2 = new int[n];
        Integer[] arr22 = new Integer[n];
        for (int i = 0; i < n; i++) {
            arr1[i] = scanner.nextInt();
            arr11[i] = getFactor(arr1[i]);
        }
        for (int i = 0; i < n; i++) {
            arr2[i] = scanner.nextInt();
            arr22[i] = getFactor(arr2[i]);
        }

        Arrays.sort(arr11, new Comparator<Integer>(){
            @Override
            public int compare(Integer o1, Integer o2) {  //不能是基本类型,故上面arr11改成Integer[]
//                return o1.compareTo(o2);
                return o2 - o1;
            }

        });
        Arrays.sort(arr22, Collections.reverseOrder());

        int res = 0;
        int j = 0;
        for (int i = 0; i < n; i++) {
            while (j < n) {
                if(arr11[i] > arr22[j]){
                    res++;
                    j++;
                    break;
                }
                j++;
            }
        }
        System.out.println(res);
    }
    //求因子个数
    public static int getFactor(int n){
        int count = 0;
        int factor = 0;
        for (factor = 1; factor*factor <= n; ++factor) {
            if(n % factor == 0){
                count = count + 2;
            }
        }
        --factor;
        if(factor * factor == n){
                --count;
        }
        return count;
    }
}

上一篇:【1.8】shell读入参,shell用户交互式输入


下一篇:反其道而行 腾讯、百度等大厂看上的不是AI换脸,而是“假脸”鉴别生意?