今日头条校招题目——贪心+排序思想

今日头条校招题目——贪心+排序思想_第1张图片

这个题一般的思路就是快速排序,然后贪心解题。但是这个题di的值太小了,题目可以说是提示了一下更优的答案,桶排序的思想解题

快速排序的话空间复杂度O(n),时间复杂度O(nlogn),利用桶排序的思想来做的话,空间复杂度O(1),时间复杂度O(n)

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int ans[] = new int[101];

        for(int i = 0; i < n; ++i) {
            int d = scanner.nextInt();
            ans[d]++;
        }

        int res = 0;
        int need = 3;
        int lastd= -1;

        for(int i = 1; i <= 100; ++i){

            if(!toBeTree(lastd, i)) {
                //System.out.println(lastd);
                res += need;
                lastd = -1;
                need = 3;
            }
            while (ans[i] > 0) {
                ans[i]--;
                need--;
                if(ans[i] == 0) lastd = i;
                if(need == 0) {
                    lastd = -1;
                    need = 3;
                }
            }
        }
        res += need == 3 ? 0 : need;
        System.out.println(res);
    }
    public static boolean toBeTree(int lastd, int cur) {
        if(lastd == -1) return true;
        if(cur - lastd > 10) return false;
        return true;
    }
}

你可能感兴趣的:(算法)