leetcode-最接近0的子数组和

xiaoxiao2021-02-28  109

public class Solution { /** * @param nums: A list of integers * @return: A list of integers includes the index of the first number * and the index of the last number */ public int[] subarraySumClosest(int[] nums) { // write your code here if(nums.length == 1){ int [] arr = {0, 0}; return arr; } ArrayList<Pair> als = new ArrayList<>(); int len = nums.length; int sum = 0; for (int i = 0; i < len; i++) { sum += nums[i]; als.add(new Pair(i, sum)); } Collections.sort(als, new Comparator<Pair>() { @Override public int compare(Pair p1, Pair p2) { return p1.sum - p2.sum; } }); int size = als.size(); int diff = Integer.MAX_VALUE; int[] result = new int[2]; for (int i = 1; i < size; i++) { int val = Math.abs(als.get(i).sum - als.get(i - 1).sum); if(val < diff){ diff = val; result[0] = als.get(i).num; result[1] = als.get(i - 1).num; if(val == 0){ break; } } } Arrays.sort(result); result[0] += 1; return result; } } class Pair{ int num; int sum; Pair(int num, int sum){ this.num = num; this.sum = sum; } }
转载请注明原文地址: https://www.6miu.com/read-39814.html

最新回复(0)