Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f289b09

Browse files
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)

AltStyle によって変換されたページ (->オリジナル) /