奇数置于数组前半部分偶数置于数组后半部分

奇数置于数组前半部分偶数置于数组后半部分

/*	剑指offer21,输入一个整数数组,实现一个函数来调整该数组中数字的顺序,
 * 				使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。
 * 	解题思路:
 * 			1.遍历数组当遇到偶数时,将该偶数后的所有数字前移一位,偶数放到数组的最后。
 * 			这种方法的时间复杂度为o(n**2)
 * 			2.双指针法,头指针指向数组头、尾指针指向数组尾
 * 			    移动头指针,如果头指针指向奇数头指针后移
 * 			    如果头指针指向偶数,尾指针指向奇数,交换两指针的值
 * 			    尾指针指向偶数,前移尾指针直到尾指针指向奇数
 * 
 * 	测试:
 * 		null
 * 		{}
 * 		{1,2,3,4,5,6}
 * 		{2,2,2,1,1,1}
 * 		{1,1,1,2,2,2}
 * 		{1,1,1,1,1,1}
 * 		{1}
 * */
public class Offer21 {
	public static void main(String[] args) {
		Offer21Solution2 solution2 = new Offer21Solution2();
		int[] nums = {1};
		solution2.exchange(nums);
		for (int i : nums) {
			System.out.print(i);
		}
	}
}

class Offer21Solution1 {
    public int[] exchange(int[] nums) {
    	if(nums==null || nums.length==1) return nums;
    	int i = 0;
    	int num = 0;
    	while(num < nums.length) {
    		//如果nums[i]是偶数,nums[i]之后的数字前移一位,nums[i]赋值到最后
    		if(nums[i]%2==0) {
    			int temp = nums[i];
    			for(int j=i;j<nums.length-1;j++) {
    				nums[j] = nums[j+1];
    			}
    			nums[nums.length-1]=temp;
    			if(nums[i]%2==0) i--;
    		}
    		i++;
    		num++;
    	}
    	return nums;
    }
}

class Offer21Solution2{
	public int[] exchange(int[] nums) {
		if(nums==null || nums.length==1 || nums.length==0) return nums;
		int head = 0;
		int tail = nums.length-1;
		while(head!=tail) {
		//	System.out.println(head+" "+tail);
			if(nums[head]%2==0) {
				if(nums[tail]%2!=0) {
					int temp = nums[head];
					nums[head] = nums[tail];
					nums[tail] = temp;
				}else if(nums[tail]%2==0) {
					while(nums[tail]%2==0) {
						if(head==tail) return nums;
						tail--;
					}
					int temp = nums[head];
					nums[head] = nums[tail];
					nums[tail] = temp;
				}
			}
			head++;
		}
		return nums;
	}
}

猜你喜欢

转载自blog.csdn.net/zfr143816/article/details/107769704