作者Rushia (みけねこ的鼻屎)
看板Marginalman
標題Re: [閒聊] 每日LeetCode
時間Thu Sep 28 22:31:54 2023
https://leetcode.com/problems/sort-array-by-parity/description
905. Sort Array By Parity
給你一個整數陣列 nums,返回排序完的 nums,這個陣列的左邊都是偶數右邊都是奇數。
思路:
1.用雙指標來處理,如果左邊的數字是偶數則左邊指標往右,如果右邊數字是奇數則右邊
指標往左,如果左邊是奇數右邊是偶數則交換兩邊的數並兩邊同時縮小。
Java Code:
--------------------------------
class Solution {
public int[] sortArrayByParity(int[] nums) {
int l = 0;
int r = nums.length - 1;
while (l < r) {
if (nums[l] % 2 == 0) {
l++;
} else if (nums[r] % 2 == 1) {
r--;
} else {
int tmp = nums[l];
nums[l] = nums[r];
nums[r] = tmp;
l++;
r--;
}
}
return nums;
}
}
--------------------------------
--
https://i.imgur.com/sjdGOE3.jpg
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.100.73.13 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1695911517.A.B3C.html
→ PyTorch: 大師 09/28 22:33
→ ZooseWu: 大師 09/28 22:53