SortableChunk [source code]

public class SortableChunk {
static
/******************************************************************************/
class Solution {
    int maximumChunks (int[] nums) {
        if (nums.length == 0)
            return 0;
        if (nums.length == 1)
            return 1;
        int chunkMin = nums[0], chunkMax = nums[0], res = 0, anchor = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] < chunkMin)
                chunkMin = nums[i];
            if (nums[i] > chunkMax)
                chunkMax = nums[i];
            if (anchor + 1 == chunkMin && i + 1 == chunkMax) {
                res++;
                anchor = i + 1;
                if (anchor < nums.length) {
                    chunkMin = nums[anchor];
                    chunkMax = nums[anchor];
                }
            }
        }
        return res;
    }
}
/******************************************************************************/

    public static void main(String[] args) {
        SortableChunk.Solution tester = new SortableChunk.Solution();
        int[][] inputs = {
            {2,1,3,5,4}, {3},
            {2,1,3,4,5}, {4},
        };
        for (int i = 0; i < inputs.length / 2; i++) {
            int[] nums = inputs[2 * i];
            int ans = inputs[2 * i + 1][0];
            System.out.println (Printer.separator ());
            int output = tester.maximumChunks (nums);
            System.out.printf ("[%s] -> %s, expected: %d\n",
                Printer.array (nums), Printer.wrapColor (output + "", output == ans ? "green" : "red"), ans
            );
        }
    }
}

Problem Description

第二题,给一个数组,长度是N,数字从1-N, 问可以最多形成几个chunk,sort完每一个chunk以后可以得到sort的array
比如[2, 1, 3, 5, 4]
最多可以形成3个chunk[2,1][3][5, 4]

follow up:
假如数字不是从1-N,怎么做. more info on 1point3acres.com

第二题两问都没有做出来,在提示下才写出了代码,跪了,很难过

results matching ""

    No results matching ""