leetcode 调整数组顺序使奇数位于偶数前面
生活随笔
收集整理的這篇文章主要介紹了
leetcode 调整数组顺序使奇数位于偶数前面
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
解法一:雙指針
public int[] Exchange(int[] nums) {int head = 0;int tail = nums.Length - 1;while(head < tail){if((nums[head] & 1) == 1){head++;continue;}else if((nums[tail] & 1) == 0){tail--;continue;}else{int temp = nums[head];nums[head] = nums[tail];nums[tail] = temp;head++;tail--;} }return nums;}解法二:快慢指針
//快慢指針public int[] Exchange(int[] nums) {int low = 0;int fast = 0;while(fast < nums.Length){if((nums[low] & 1) == 0){if((nums[fast] & 1) == 1){int temp = nums[low];nums[low] = nums[fast];nums[fast] = temp;low++;}fast++;}else{low++;fast++;} }return nums;}?優化點1:用與操作代替求余操作
如:if((nums[head]?&?1)?==?1)
?優化點2:用異或實現交換操作,速度更快的同時節約一個臨時變量
nums[slow] ^= nums[fast];
nums[fast] ^= nums[slow];
nums[slow] ^= nums[fast];
?
?
總結
以上是生活随笔為你收集整理的leetcode 调整数组顺序使奇数位于偶数前面的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Unity降版本的蛋疼操作
- 下一篇: 网易电竞NeXT2020冬季赛《我的世界