当前位置:网站首页>[leetcode refers to offer 21. Adjust the array order so that odd numbers precede even numbers (simple)]

[leetcode refers to offer 21. Adjust the array order so that odd numbers precede even numbers (simple)]

2022-04-23 21:21:00 Minaldo7

subject :

Enter an array of integers , Implement a function to adjust the order of the Numbers in the array , Make all odd numbers in the first half of the array , All even numbers are in the second half of the array .

Example :

Input :nums = [1,2,3,4]
Output :[1,3,2,4]
notes :[3,1,2,4] And one of the right answers .

Tips :

0 <= nums.length <= 50000
0 <= nums[i] <= 10000

source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/diao-zheng-shu-zu-shun-xu-shi-qi-shu-wei-yu-ou-shu-qian-mian-lcof
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .

The problem solving process :

Double pointer

class Solution {
    
    public int[] exchange(int[] nums) {
    
        int start = 0, end = nums.length-1, temp = 0;;
        while(start < end){
    
            while(start < end && nums[start] % 2 == 1){
    
                start++;
            }
            while(start < end && nums[end] % 2 == 0){
    
                end--;
            }
            if(start < end){
    
                temp = nums[start];
                nums[start] = nums[end];
                nums[end] = temp;
            }
                
        }
        return nums;
    }
}

Execution results :

 Insert picture description here

版权声明
本文为[Minaldo7]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/111/202204210544479098.html