编程小技巧

技巧 - stream 找最大值

https://leetcode.cn/problems/all-divisions-with-the-highest-score-of-a-binary-array/description/

public class test {
    public static void main(String[] args) {
        int[] num = new int[]{0, 0, 1, 0};
        maxScoreIndices(num);
    }


    public static List<Integer> maxScoreIndices(int[] nums) {
        int left = 0, rigth = Arrays.stream(nums).sum();

        int length = nums.length;
        int[] temp = new int[length + 1];
        temp[0] = rigth;

        int i = 1;
        for (; i < length; i++) {
            if (nums[i - 1] == 0) {
                left++;
            } else {
                rigth--;
            }
            temp[i] = left + rigth;
        }
        if (nums[i - 1] == 0)
            left++;
        temp[i] = left;

        List<Integer> ans = new ArrayList<>();
        OptionalInt max = Arrays.stream(temp).max();
        for (i = 0; i < length + 1; i++) {
            if (OptionalInt.of(temp[i]).equals(max)) {
                System.out.println(i);
                ans.add(i);
            }
        }
        return ans;
    }
}

优化后:

public List<Integer> maxScoreIndices(int[] nums) {
	int len = nums.length;
	int zeroCount = (int) Arrays.stream(nums).filter(num -> num == 0).count();
	int  len - zeroCount;
	int[] record = new int[len + 1];
	int left = 0;
	int right = oneCount;
	record[0] = left + right;
	int index = 0;
	while (index < len) {
	    if (nums[index] == 0) {
	        left++;
	    } else {
	        right--;
	    }
	    record[index + 1] = left + right;
	    index++;
	}
	int max = Arrays.stream(record).max().getAsInt();
	return IntStream.range(0, len + 1).filter(i -> record[i] == max).boxed().collect(Collectors.toList());
}

你可能感兴趣的:(算法,算法,leetcode,数据结构)