File tree Expand file tree Collapse file tree 3 files changed +96
-0
lines changed
3190-Find Minimum Operations to Make All Elements Divisible by Three Expand file tree Collapse file tree 3 files changed +96
-0
lines changed Original file line number Diff line number Diff line change 1+ # 3190. Find Minimum Operations to Make All Elements Divisible by Three
2+
3+ You are given an integer array ` nums ` .
4+ In one operation, you can add or subtract 1 from any element of ` nums ` .
5+
6+ Return the minimum number of operations to make all elements of ` nums ` divisible by 3.
7+
8+ ** Constraints:**
9+
10+ - ` 1 <= nums.length <= 50 `
11+ - ` 1 <= nums[i] <= 50 `
12+
13+ ## 基礎思路
14+
15+ 本題要求讓陣列 ` nums ` 中的所有元素都能被 3 整除,而每次操作允許對任一元素加 1 或減 1。
16+ 要判斷每個元素需要幾次操作,使其變成 3 的倍數,可以觀察以下性質:
17+
18+ - 若一個數 ` x ` 對 3 取餘數為 ` 0 ` ,即 ` x % 3 == 0 ` ,則它已經能被 3 整除,不需任何操作。
19+ - 若餘數為 ` 1 ` ,只要加 1 或減 1 就能變成 3 的倍數。
20+ - 若餘數為 ` 2 ` ,同樣加 1 或減 1 即可轉為 3 的倍數。
21+
22+ 因此,每個非 3 的倍數的數字都只需要 ** 1 次操作** 就能修正。
23+ 整體答案就是計算整個陣列中餘數不為 0 的元素個數。
24+
25+ 本題所需的操作方式非常直接,因此能以線性掃描完成,時間複雜度為 $O(n)$。
26+
27+ ## 解題步驟
28+
29+ ### Step 1:初始化操作次數並取得陣列長度
30+
31+ 建立計數變數 ` totalOperations ` 與陣列長度 ` length ` ,用於後續統計。
32+
33+ ``` typescript
34+ // 總共需要的操作次數
35+ let totalOperations = 0 ;
36+
37+ const length = nums .length ;
38+ ```
39+
40+ ### Step 2:逐一檢查每個元素是否可被 3 整除
41+
42+ 若 ` value % 3 !== 0 ` ,此元素需要 1 次操作,因此累加計數。
43+
44+ ``` typescript
45+ for (let index= 0 ; index < length ; index ++ ) {
46+ const value = nums [index ];
47+ const remainder = value % 3 ;
48+
49+ // 若餘數不為 0,則此元素需要 1 次操作
50+ if (remainder !== 0 ) {
51+ totalOperations = totalOperations + 1 ;
52+ }
53+ }
54+ ```
55+
56+ ### Step 3:回傳最終操作次數
57+
58+ 所有元素處理完後,即可回傳累積結果。
59+
60+ ``` typescript
61+ return totalOperations ;
62+ ```
63+
64+ ## 時間複雜度
65+
66+ - 單一迴圈掃描所有元素,每個元素判斷成本為 $O(1)$;
67+ - ** 總時間複雜度為 $O(n)$** 。
68+
69+ > $O(n)$
70+
71+ ## 空間複雜度
72+
73+ - 僅使用常數額外變數;
74+ - ** 總空間複雜度為 $O(1)$** 。
75+
76+ > $O(1)$
Original file line number Diff line number Diff line change 1+ function minimumOperations ( nums : number [ ] ) : number {
2+ // Total operations required to fix all elements
3+ let totalOperations = 0 ;
4+
5+ const length = nums . length ;
6+ for ( let index = 0 ; index < length ; index ++ ) {
7+ const value = nums [ index ] ;
8+ const remainder = value % 3 ;
9+
10+ // If remainder is not zero, we need exactly 1 operation for this element
11+ if ( remainder !== 0 ) {
12+ totalOperations = totalOperations + 1 ;
13+ }
14+ }
15+
16+ return totalOperations ;
17+ }
Original file line number Diff line number Diff line change 1+ function minimumOperations ( nums : number [ ] ) : number {
2+
3+ }
You can’t perform that action at this time.
0 commit comments