Leetcode : 1590. Make Sum Divisible by P

Given an array of positive integers nums, remove the smallest subarray (possibly empty) such that the sum of the remaining elements is divisible by p. It is not allowed to remove the whole array.

Return the length of the smallest subarray that you need to remove, or -1 if it's impossible.

A subarray is defined as a contiguous block of elements in the array.

分析:

移除subarray 只需要固定两个端点   (subsequence 移除不一定连续的子序列)

1、前缀和 + 暴力解法 (超过时间了 没通过 但逻辑应该是没问题的)

class Solution {
public:
    int minSubarray(vector<int>& nums, int p) {
        int n = nums.size();
        vector<int> presum(n, 0);
        presum[0] = nums[0];
        int res = INT_MAX;
        int sum = 0; 
        for(int i = 0; i < n; i++) {
            sum += nums[i];
        }
        int m = sum % p;
        if(m == 0)return 0;
        for(int i = 1; i < n; i++) {
            presum[i] = presum[i - 1] + nums[i]; 
        }
        for(int i = 0; i < n; i++) {
            for(int j = i + 1; j < n; j++) {
                if((presum[j] - presum[i]) % p == m) {
                    res = min(res, j - i);
                }
            }
        }
        if(res == INT_MAX) return -1;
        else return res;
    }
};

2、前缀和 + 哈希表

sum[i: j] = presum[j]  - presum[i - 1]

   rem            r                 r - rem

运行出现的问题:

1、r - rem 可能会< 0  所以需要对 该数加上一个p再对p取余  (r - rem + p)%p

2、nums中的元素数量太大 会产生 越界   所以不要一次性累加  每次加完后取余

3、res不能等于或超过数组长度  所以 res >= nums.size()的时候要return -1

class Solution {
public:
    int minSubarray(vector<int>& nums, int p) {
        unordered_map<int,int> mymap;
        mymap[0] = -1;
        int rem = 0;
        int res = INT_MAX;
        for(auto n:nums) {
            rem = (rem + n) % p; // 求最后的余数 每次取余 避免数太大 越界
        }
        if(rem == 0) return 0;
        int r = 0;
        for(int j = 0; j < nums.size(); j++) {
            r = (r + nums[j]) % p;
            int rr = (r - rem + p) % p;
            if(mymap.find(rr) != mymap.end()) {
                int i = mymap[rr] + 1;
                res = min(res, j - i + 1);
            }
            mymap[r % p] = j;
        }
        if(res < nums.size()) return res;
        else return -1;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_44189622/article/details/129451747