We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent a9f3290 commit f289b09Copy full SHA for f289b09
Daily Question/2025/Martch/Apply Operations to an Array
@@ -0,0 +1,26 @@
1
+想法:用一個 index 紀錄非0的值的末尾位置,每次只要有要加入的值就加在末尾並更新位置即可
2
+因為 index 永遠落後於 i , 所以不需擔心更新到前面的問題
3
+
4
+Time Complexity : O(n) for traversing the array
5
+Space Complexity : O(n) for the answer array
6
7
+class Solution {
8
+public:
9
+ vector<int> applyOperations(vector<int>& nums) {
10
+ int index = 0 ;
11
+ for(int i = 0 ; i < nums.size() ; i++) {
12
+ if ( nums[i] != 0 && i < nums.size() - 1 && nums[i] == nums[i + 1] ) {
13
+ nums[index++] = nums[i] * 2 ;
14
+ nums[i + 1] = 0 ;
15
+ }
16
+ else if ( nums[i] != 0 ) {
17
+ nums[index++] = nums[i] ;
18
19
20
21
+ for(int i = index ; i < nums.size() ; i++)
22
+ nums[i] = 0 ;
23
24
+ return nums ;
25
26
+};
0 commit comments