Re: [閒聊] 每日LeetCode已回收
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
→
09/28 22:33,
2年前
, 1F
09/28 22:33, 1F
→
09/28 22:53,
2年前
, 2F
09/28 22:53, 2F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 423 之 719 篇):