Skip to content

Commit f289b09

Browse files
authored
Create Apply Operations to an Array
1 parent a9f3290 commit f289b09

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy