51 lines
2.2 KiB
Java
51 lines
2.2 KiB
Java
package com.iqiaoxu.code;
|
|
|
|
import javafx.util.Pair;
|
|
|
|
import java.util.ArrayList;
|
|
import java.util.Arrays;
|
|
import java.util.Collections;
|
|
import java.util.List;
|
|
|
|
public class Solution {
|
|
public int xorOperation(int n, int start) {
|
|
return (start & 3) < 2 ? ((n & 1) == 0) ? (n & 3) : (start + 2 * n - 3 + (n & 3)) : ((n & 1) == 0) ? ((start + (n - 1) * 2) ^ (start - 2 + (n & 3))) : (start + 1 - (n & 3));
|
|
}
|
|
|
|
public int mySqrt(int x) {
|
|
double xHalf = 0.5 * x;
|
|
long i = Double.doubleToLongBits(x);
|
|
i = 0x1FF7A3BEA91D9B1BL + (i >> 1);
|
|
double f = Double.longBitsToDouble(i);
|
|
f = f * 0.5 + xHalf / f;
|
|
f = f * 0.5 + xHalf / f;
|
|
f = f * 0.5 + xHalf / f;
|
|
return (int) f;
|
|
}
|
|
|
|
public int deleteAndEarn(int[] nums) {
|
|
List<Integer> sum = new ArrayList<>(Collections.nCopies(Arrays.stream(nums).max().orElse(0) + 1, 0));
|
|
Arrays.stream(nums).forEach(v -> sum.set(v, sum.get(v) + v));
|
|
return sum.stream().reduce(new Pair<>(0, 0), ((acc, x) -> new Pair<>(acc.getValue(), Integer.max(acc.getKey() + x, acc.getValue()))), (a, b) -> new Pair<>(0, 0)).getValue();
|
|
}
|
|
|
|
public int rob(int[] nums) {
|
|
return Arrays.stream(nums).boxed().reduce(new Pair<>(0, 0), ((a, x) -> new Pair<>(a.getValue(), Integer.max(a.getKey() + x, a.getValue()))), (a, b) -> new Pair<>(0, 0)).getValue();
|
|
}
|
|
|
|
public int rob2(int[] nums) {
|
|
return Integer.max(Integer.max(Arrays.stream(nums).boxed().limit(nums.length - 1).reduce(new Pair<>(0, 0), ((a, x) -> new Pair<>(a.getValue(), Integer.max(a.getKey() + x, a.getValue()))), (a, b) -> new Pair<>(0, 0)).getValue(), Arrays.stream(nums).boxed().skip(1).reduce(new Pair<>(0, 0), ((a, x) -> new Pair<>(a.getValue(), Integer.max(a.getKey() + x, a.getValue()))), (a, b) -> new Pair<>(0, 0)).getValue()), nums[0]);
|
|
}
|
|
|
|
/**
|
|
* 268.丢失的数字
|
|
*
|
|
* @param nums 数组
|
|
* @return 丢失的数字
|
|
* @see <a href="https://leetcode-cn.com/problems/missing-number/">原题链接</a>
|
|
*/
|
|
public int missingNumber(int[] nums) {
|
|
return new int[]{nums.length, 1, nums.length + 1, 0}[nums.length & 3] ^ Arrays.stream(nums).reduce(0, (o, n) -> o ^ n);
|
|
}
|
|
}
|