1+ /**
2+ * 2460. Apply Operations to an Array
3+ *
4+ * 操作n - 1次
5+ * 若nums[i] === nums[i +1],則將nums[i] * 2,將nums[i+1]改成0
6+ * 完成所有操作,將所有的0移到陣列最後面
7+ * 回傳陣列
8+ * @param {number[] } nums
9+ * @return {number[] }
10+ */
11+ var applyOperations = function ( nums ) {
12+ let j = 0 ;
13+ for ( let i = 0 ; i < nums . length - 1 ; ++ i ) {
14+ if ( nums [ i ] === nums [ i + 1 ] ) {
15+ nums [ i ] *= 2 ;
16+ nums [ i + 1 ] = 0 ;
17+ }
18+ }
19+ for ( let i = 0 ; i < nums . length ; ++ i ) {
20+ if ( nums [ i ] !== 0 ) {
21+ nums [ j ] = nums [ i ] ;
22+ j ++ ;
23+ }
24+ }
25+ while ( j < nums . length ) {
26+ nums [ j ++ ] = 0 ;
27+ }
28+ return nums ;
29+ } ;
30+ let nums = [ 1 , 2 , 2 , 1 , 1 , 0 ]
31+ // Output: [1,4,2,0,0,0]
32+ // Explanation: We do the following operations:
33+ // i = 0: nums[0] and nums[1] are not equal, so we skip this operation.
34+ // i = 1: nums[1] and nums[2] are equal, we multiply nums[1] by 2 and change nums[2] to 0. The array becomes [1,4,0,1,1,0].
35+ // i = 2: nums[2] and nums[3] are not equal, so we skip this operation.
36+ // i = 3: nums[3] and nums[4] are equal, we multiply nums[3] by 2 and change nums[4] to 0. The array becomes [1,4,0,2,0,0].
37+ // i = 4: nums[4] and nums[5] are equal, we multiply nums[4] by 2 and change nums[5] to 0. The array becomes [1,4,0,2,0,0].
38+ // After that, we shift the 0's to the end, which gives the array [1,4,2,0,0,0].
39+ console . log ( applyOperations ( nums ) ) ;
0 commit comments