Skip to content

Latest commit

 

History

History
189 lines (160 loc) · 4.58 KB

File metadata and controls

189 lines (160 loc) · 4.58 KB

中文文档

Description

You are given an integer array nums and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Note that this modifies the array for future operations.

Return the minimum number of operations to reduce x to exactly 0 if it's possible, otherwise, return -1.

 

Example 1:

Input: nums = [1,1,4,2,3], x = 5
Output: 2
Explanation: The optimal solution is to remove the last two elements to reduce x to zero.

Example 2:

Input: nums = [5,6,7,8,9], x = 4
Output: -1

Example 3:

Input: nums = [3,2,20,1,1,3], x = 10
Output: 5
Explanation: The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero.

 

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 104
  • 1 <= x <= 109

Solutions

Python3

class Solution:
    def minOperations(self, nums: List[int], x: int) -> int:
        x = sum(nums) - x
        n = len(nums)
        s = 0
        seen = {0: -1}
        ans = float('inf')
        for i, v in enumerate(nums):
            s += v
            if s not in seen:
                seen[s] = i
            if s - x in seen:
                j = seen[s - x]
                ans = min(ans, n - (i - j))
        return -1 if ans == float('inf') else ans

Java

class Solution {
    public int minOperations(int[] nums, int x) {
        x = -x;
        for (int v : nums) {
            x += v;
        }
        int s = 0;
        int n = nums.length;
        Map<Integer, Integer> seen = new HashMap<>();
        seen.put(0, -1);
        int ans = Integer.MAX_VALUE;
        for (int i = 0; i < n; ++i) {
            s += nums[i];
            seen.putIfAbsent(s, i);
            if (seen.containsKey(s - x)) {
                int j = seen.get(s - x);
                ans = Math.min(ans, n - (i - j));
            }
        }
        return ans == Integer.MAX_VALUE ? -1 : ans;
    }
}

TypeScript

function minOperations(nums: number[], x: number): number {
    const total = nums.reduce((a, c) => a + c, 0);
    if (total < x) return -1;
    // 前缀和 + 哈希表, 求何为total - x的最长子序列
    const n = nums.length;
    const target = total - x;
    let hashMap = new Map();
    hashMap.set(0, -1);
    let pre = 0;
    let ans = -1;
    for (let right = 0; right < n; right++) {
        pre += nums[right];
        if (!hashMap.has(pre)) {
            hashMap.set(pre, right);
        }
        if (hashMap.has(pre - target)) {
            let left = hashMap.get(pre - target);
            ans = Math.max(right - left, ans)
        }
    }
    return ans == -1 ? -1 : n - ans;
};

C++

class Solution {
public:
    int minOperations(vector<int>& nums, int x) {
        x = -x;
        for (int& v : nums) x += v;
        int s = 0, n = nums.size();
        unordered_map<int, int> seen;
        seen[0] = -1;
        int ans = INT_MAX;
        for (int i = 0; i < n; ++i)
        {
            s += nums[i];
            if (!seen.count(s)) seen[s] = i;
            if (seen.count(s - x))
            {
                int j = seen[s - x];
                ans = min(ans, n - (i - j));
            }
        }
        return ans == INT_MAX ? -1 : ans;
    }
};

Go

func minOperations(nums []int, x int) int {
	x = -x
	for _, v := range nums {
		x += v
	}
	s, n := 0, len(nums)
	seen := map[int]int{0: -1}
	ans := math.MaxInt32
	for i, v := range nums {
		s += v
		if _, ok := seen[s]; !ok {
			seen[s] = i
		}
		if j, ok := seen[s-x]; ok {
			ans = min(ans, n-(i-j))
		}
	}
	if ans == math.MaxInt32 {
		return -1
	}
	return ans
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

...