922:按奇偶排序数组 II

This commit is contained in:
huangge1199 2021-06-07 11:19:22 +08:00
parent 31978afb9a
commit 8dfe5d64e9
2 changed files with 82 additions and 0 deletions

View File

@ -0,0 +1,55 @@
//给定一个非负整数数组 A A 中一半整数是奇数一半整数是偶数
//
// 对数组进行排序以便当 A[i] 为奇数时i 也是奇数 A[i] 为偶数时 i 也是偶数
//
// 你可以返回任何满足上述条件的数组作为答案
//
//
//
// 示例
//
// 输入[4,2,5,7]
//输出[4,5,2,7]
//解释[4,7,2,5][2,5,4,7][2,7,4,5] 也会被接受
//
//
//
//
// 提示
//
//
// 2 <= A.length <= 20000
// A.length % 2 == 0
// 0 <= A[i] <= 1000
//
//
//
// Related Topics 排序 数组
// 👍 208 👎 0
package leetcode.editor.cn;
//922:按奇偶排序数组 II
public class SortArrayByParityIi{
public static void main(String[] args) {
//测试代码
Solution solution = new SortArrayByParityIi().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int[] sortArrayByParityII(int[] nums) {
for (int i = 0; i < nums.length - 1; i++) {
int j = i + 1;
while ((nums[i] - i) % 2 != 0) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
j++;
}
}
return nums;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,27 @@
<p>给定一个非负整数数组&nbsp;<code>A</code> A 中一半整数是奇数,一半整数是偶数。</p>
<p>对数组进行排序,以便当&nbsp;<code>A[i]</code> 为奇数时,<code>i</code>&nbsp;也是奇数;当&nbsp;<code>A[i]</code>&nbsp;为偶数时, <code>i</code> 也是偶数。</p>
<p>你可以返回任何满足上述条件的数组作为答案。</p>
<p>&nbsp;</p>
<p><strong>示例:</strong></p>
<pre><strong>输入:</strong>[4,2,5,7]
<strong>输出:</strong>[4,5,2,7]
<strong>解释:</strong>[4,7,2,5][2,5,4,7][2,7,4,5] 也会被接受。
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ol>
<li><code>2 &lt;= A.length &lt;= 20000</code></li>
<li><code>A.length % 2 == 0</code></li>
<li><code>0 &lt;= A[i] &lt;= 1000</code></li>
</ol>
<p>&nbsp;</p>
<div><div>Related Topics</div><div><li>排序</li><li>数组</li></div></div>\n<div><li>👍 208</li><li>👎 0</li></div>