【一次过】Lintcode 373:奇偶分割数组

 

分割一个整数数组,使得奇数在前偶数在后。

样例

给定 [1, 2, 3, 4],返回 [1, 3, 2, 4]

挑战

在原数组中完成,不使用额外空间。

解题思路1:

    双指针法。类似于Lintcode 213:字符串压缩,设置两个指针i, j,从头遍历,i指向第一次出现偶数,j从i开始指向第一次出现的奇数,然后将两者指向的元素交换,继续。

class Solution {
public:
    /*
     * @param nums: an array of integers
     * @return: nothing
     */
    void partitionArray(vector<int> &nums) 
    {
        // write your code here
        for(int i=0,j=0;i<nums.size();j=i)
        {
            if(nums[i]%2 == 0)
            {
                while(nums[j]%2 == 0 && j<nums.size())
                    j++;
                
                swap(nums[i],nums[j]);
            }
            i++;
        }
    }
};

解题思路2:

    同样采用双指针,只是一个指针在首,一个指针在尾。

class Solution {
public:
    /*
     * @param nums: an array of integers
     * @return: nothing
     */
    void partitionArray(vector<int> &nums) 
    {
        // write your code here
        int i=0;
        int j=nums.size()-1;
        
        while(i<j)
        {
            if(nums[i]%2 == 0)
            {
                swap(nums[i],nums[j]);
                j--;
            }
            else
                i++;
        }
    }
};

JAVA代码:

public class Solution {
    /*
     * @param nums: an array of integers
     * @return: nothing
     */
    public void partitionArray(int[] nums) {
        // write your code here
        int i = 0;
        int j = nums.length-1;
        
        while(i<j){
            if(nums[i]%2 == 0){
                swap(nums , i , j--);
            }else{
                i++;
            }
        }
    }
    
    public void swap(int[] nums , int i , int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值