题目
题目链接:
https://www.nowcoder.com/practice/3e1fd3d19fb0479d94652d49c7e1ead1
思路
本答案利用前缀和解答,Java,Go答案通过,但是同样的代码用PHP的话有一个测试用例超时
应该还有更优秀的答案,后面找到更优答案再更新博客
Java代码
import java.util.*;public class Solution {/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可*** @param nums int整型ArrayList* @param k int整型* @return int整型*/public int shortestSubarray (ArrayList<Integer> nums, int k) {//前缀和int n = nums.size();int[] sum = new int[n + 1];for (int i = 0; i < n; i++) {sum[i + 1] = sum[i] + nums.get(i);sum[i + 1]%=1000000007; //关键if (nums.get(i) == k) return 1;}int ans = 0x7fffffff;for (int i = 0; i <= n ; i++) {if (sum[i] >= k) {ans = Math.min(ans, i);for (int j = i ; j >= 0 ; j--) {int diff = sum[i] - sum[j];if (diff >= k) {ans = Math.min(ans, i - j);break;}}}}if (ans == 0x7fffffff)return -1;return ans;}
}
Go代码
package main/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可*** @param nums int整型一维数组* @param k int整型* @return int整型*/
func shortestSubarray(nums []int, k int) int {//前缀和n := len(nums)ans := 0x7fffffffsum := make([]int, n+1)for i := 0; i < n; i++ {sum[i+1] = sum[i] + nums[i]if nums[i] == k {return 1}}for i := 0; i <= n; i++ {if sum[i] >= k { //剪枝if sum[i] >= k {if i < ans {ans = i}}for j := i; j >= 0; j-- {diff := sum[i] - sum[j]if diff >= k {if i-j < ans {ans = i - j}break}}}}if ans == 0x7fffffff {return -1}return ans
}