每天一道算法题系列:
来源:力扣(LeetCode)
本题链接:https://leetcode-cn.com/problems/diao-zheng-shu-zu-shun-xu-shi-qi-shu-wei-yu-ou-shu-qian-mian-lcof/
来源是力扣,大家喜欢可以去力扣中文网做相应的其他的题,某浏览器直接搜力扣即可。
本题难度是简单
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。
示例:
输入:nums = [1,2,3,4]
输出:[1,3,2,4]
注:[3,1,2,4] 也是正确的答案之一。
/*
第一种解法就很简单,我们只需要一个for循环就行,因为文中不注意排序,所以就有很多操作空间
看这个解法,无非就是遍历的时候,把奇数放前面,把偶数放后面
然后需要注意的一点就是不能放重复了
白话一点就是东凑西凑的给补上去,已完成为目的
*/
public int[] exchange(int[] nums) {
int[] xx = new int[nums.length];
int count = 0 ;
int cc = 0 ;
for(int i = 0 ; i < nums.length ; i++){
if((nums[i] & 1 )!= 0){
xx[cc] = nums[i];
cc ++;
}else{
++count ;
xx[nums.length - count] = nums[i];
}
}
return xx ;
}
这里突然发现,位运算太好用了,位运算nums[left] & 1 ==0 虽然和 nums[left] % 2 ==0 的结果是一样的,但是位运算会快一点
/*
第二种解法就是双指针的形式,left指向第一个,right指向第二个
我们再循环的时候,需要进行比较,left遇见偶数就等着后right遇见的奇数进行交换顺序
*/
public int[] exchange(int[] nums) {
int[] xx = new int[nums.length];
int left = 0 ;
int right = nums.length -1 ;
while(left <= right){
if((nums[left] & 1) == 0 && (nums[right] & 1) != 0){
int tmp = nums[left];
nums[left] = nums[right];
nums[right] = tmp;
left++;
right--;
}
if((nums[left] & 1) != 0)
left++;
if((nums[right] & 1) == 0)
right--;
}
return nums;
}
上一篇文章:每天一道算法题系列三十一之删除链表的节点
如果本篇内容有问题,请第一时间联系我,我会第一时间修改。
谢谢大家。