1652. Defuse the Bomb


문제 링크


내 코드

다 구해도 될 것 같아서 다 구하기.

  • 0ms, 10.42MB
class Solution {
public:
    vector<int> decrypt(vector<int>& code, int k) {
        int n = static_cast<int>(code.size());
        
        vector<int> answer(n, 0);
        if( k ==0 ) return answer;
        
        if(k > 0) {
            for(int i{};i<n;++i) {
                for(int j{1};j<=k;++j) {
                    answer[i] += code[ (i + j) % n];
                }
            }
        }
        else if (k < 0) {
            for(int i{};i<n;++i) {
                for(int j{-1};j>=k;--j) {
                    answer[i] += code[ (i + j + n) % n];
                }
            }
        }

        return answer;
    }
};

Solution

Approach 1: Brute Force

  • 0ms, 10.31MB
  • Complexity
    • Let nn be the size of the given code array.
    • Time Complexity: O(nk)O(n \cdot |k|)
    • Space Complexity: O(n)O(n)
class Solution {
public:
    vector<int> decrypt(vector<int>& code, int k) {
        vector<int> result(code.size(), 0);
        if (k == 0) {
            return result;
        }
        for (int i = 0; i < result.size(); i++) {
            if (k > 0) {
                for (int j = i + 1; j < i + k + 1; j++) {
                    result[i] += code[j % code.size()];
                }
            } else {
                for (int j = i - abs(k); j < i; j++) {
                    result[i] += code[(j + code.size()) % code.size()];
                }
            }
        }
        return result;
    }
};

Approach 2: Sliding Window

  • 0ms, 10.42MB
  • Complexity
    • Let nn be the size of the given code array.
    • Time Complexity: O(n)O(n)
    • Space Complexity: O(n)O(n)
class Solution {
public:
    vector<int> decrypt(vector<int>& code, int k) {
        vector<int> result(code.size(), 0);
        if (k == 0) return result;
        // Define the initial window and initial sum
        int start = 1, end = k, sum = 0;
        // If k < 0, the starting point will be end of the array.
        if (k < 0) {
            start = code.size() - abs(k);
            end = code.size() - 1;
        }
        for (int i = start; i <= end; i++) sum += code[i];
        // Scan through the code array as i moving to the right, update the
        // window sum.
        for (int i = 0; i < code.size(); i++) {
            result[i] = sum;
            sum -= code[start % code.size()];
            sum += code[(end + 1) % code.size()];
            start++;
            end++;
        }
        return result;
    }
};