mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Update 0922.按奇偶排序数组Ⅱ.md 添加了Java版本的两种方法
This commit is contained in:
@ -147,6 +147,59 @@ class Solution {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### java
|
||||||
|
|
||||||
|
```java
|
||||||
|
//方法一:采用额外的数组空间
|
||||||
|
class Solution {
|
||||||
|
public int[] sortArrayByParityII(int[] nums) {
|
||||||
|
//定义结果数组 result
|
||||||
|
int[] result = new int[nums.length];
|
||||||
|
int even = 0, odd = 1;
|
||||||
|
for(int i = 0; i < nums.length; i++){
|
||||||
|
//如果为偶数
|
||||||
|
if(nums[i] % 2 == 0){
|
||||||
|
result[even] = nums[i];
|
||||||
|
even += 2;
|
||||||
|
}else{
|
||||||
|
result[odd] = nums[i];
|
||||||
|
odd += 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
```java
|
||||||
|
//方法二:不采用额外的数组空间
|
||||||
|
class Solution922 {
|
||||||
|
public int[] sortArrayByParityII(int[] nums) {
|
||||||
|
//定义双指针
|
||||||
|
int oddPoint = 1, evenPoint = 0;
|
||||||
|
//开始移动并交换,最后一层必然为相互交换后再移动或者相同直接移动
|
||||||
|
while(oddPoint < nums.length && evenPoint < nums.length){
|
||||||
|
//进行判断
|
||||||
|
if(nums[oddPoint] % 2 == 0 && nums[evenPoint] % 2 == 1){ //如果均不满足
|
||||||
|
int temp = 0;
|
||||||
|
temp = nums[oddPoint];
|
||||||
|
nums[oddPoint] = nums[evenPoint];
|
||||||
|
nums[evenPoint] = temp;
|
||||||
|
oddPoint += 2;
|
||||||
|
evenPoint += 2;
|
||||||
|
}else if(nums[oddPoint] % 2 == 0 && nums[evenPoint] % 2 == 0){ //偶数满足
|
||||||
|
evenPoint += 2;
|
||||||
|
}else if(nums[oddPoint] % 2 == 1 && nums[evenPoint] % 2 == 1){ //奇数满足
|
||||||
|
oddPoint += 2;
|
||||||
|
}else{
|
||||||
|
oddPoint += 2;
|
||||||
|
evenPoint += 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nums;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
### Python3
|
### Python3
|
||||||
|
|
||||||
```python
|
```python
|
||||||
|
Reference in New Issue
Block a user