You have a bomb to defuse, and your time is running out! Your informer will provide you with a circular array code
of length of n
and a key k
.
To decrypt the code, you must replace every number. All the numbers are replaced simultaneously.
- If
k > 0
, replace theith
number with the sum of the nextk
numbers. - If
k < 0
, replace theith
number with the sum of the previousk
numbers. - If
k == 0
, replace theith
number with0
.
As code
is circular, the next element of code[n-1]
is code[0]
, and the previous element of code[0]
is code[n-1]
.
Given the circular array code
and an integer key k
, return the decrypted code to defuse the bomb!
Example 1:
Input: code = [5,7,1,4], k = 3
Output: [12,10,16,13]
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class DefuseBomb {public static void main(String[] args) {int[] code = { 5, 7, 1, 4 };int k = 3;int[] ans = decrypt(code, k);System.out.println(Arrays.toString(ans));}static int[] decrypt(int[] code, int k) {List<Integer> res = new ArrayList<Integer>();int n = code.length;if (k == 0) {for (int i = 0; i < code.length; i++)res.add(0);} else if (k > 0) {int p = k;for (int i = 0; i < n; i++) {int sum = 0;k = p;for (int j = i + 1; j < n && k > 0; j++) {k--;sum += code[j];}for (int j = 0; k > 0; j++) {sum += code[j];k--;}res.add(sum);}} else if (k < 0) {int p = -k;for (int i = 0; i < n; i++) {k = p;int sum = 0;for (int j = i - 1; j >= 0 && k > 0; j--) {sum += code[j];k--;}for (int j = n - 1; j >= 0 && k > 0; j--) {sum += code[j];k--;}res.add(sum);}}return res.stream().mapToInt(Integer::intValue).toArray();}}
C++
#include <bits/stdc++.h>using namespace std;vector<int> decrypt(vector<int> &code, int k){vector<int> res;int n = code.size();if (k == 0){for (int i = 0; i < code.size(); i++)res.push_back(0);}else if (k > 0){int p = k;for (int i = 0; i < n; i++){int sum = 0;k = p;for (int j = i + 1; j < n && k > 0; j++){k--;sum += code[j];}for (int j = 0; k > 0; j++){sum += code[j];k--;}res.push_back(sum);}}else if (k < 0){int p = -k;for (int i = 0; i < n; i++){k = p;int sum = 0;for (int j = i - 1; j >= 0 && k > 0; j--){sum += code[j];k--;}for (int j = n - 1; j >= 0 && k > 0; j--){sum += code[j];k--;}res.push_back(sum);}}return res;}int main(){vector<int> code = {5, 7, 1, 4};int k = 3;vector<int> ans = decrypt(code, k);cout << "[";for (int i = 0; i < ans.size() - 1; i++)cout << ans[i] << ",";cout << ans[ans.size() - 1] << "]";return 0;}
No comments:
Post a Comment