Java Stream & LeetCode —— 两数之和

65 阅读1分钟
class Solution {
    public int[] twoSum(int[] nums, int target) {
        return IntStream.range(0, nums.length)
                .boxed()
                .flatMap(i -> IntStream.range(i + 1, nums.length).mapToObj(j -> new int[]{i, j}))
                .filter(pair -> nums[pair[0]] + nums[pair[1]] == target)
                .findFirst()
                .orElseThrow();
    }
}

image.png