iT邦幫忙

2025 iThome 鐵人賽

DAY 6
0

題目介紹

  • 編號:283
  • 類型:Array, Two Pointers
  • 難度:easy
  • 題目連結:https://leetcode.com/problems/move-zeroes/description/
  • 描述:給一個整數數列,將所有0移到最後,同時要保持其他非零的數的順序

解題成功圖片:
https://ithelp.ithome.com.tw/upload/images/20250920/20178840gni6ebouo0.jpg

notion筆記截圖:
https://ithelp.ithome.com.tw/upload/images/20250920/20178840EaJ6QN0YMb.jpg
https://ithelp.ithome.com.tw/upload/images/20250920/20178840lHtGDXHWIm.jpg

延伸解法(直接搬移非零值):

  • 適合用在資料很大但零很少的時候,但當元素本來就有排好,這個做法會做更多不必要的交換。
    public void moveZeroes(int[] nums) {
    int nonZeroIndex = 0;

for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
int temp = nums[i];
nums[i] = nums[nonZeroIndex];
nums[nonZeroIndex] = temp;

    nonZeroIndex++;
}

}
}


上一篇
<Day 5> Merge Sorted Array
下一篇
<DAY7> - Squares of a Sorted Array
系列文
「用 LeetCode 挑戰 30 天,打造扎實的程式邏輯力」- 結合Notion記錄學習筆記7
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言