[Leetcode][第75题][JAVA][颜色分类][双(三)指针][计数排序]
生活随笔
收集整理的這篇文章主要介紹了
[Leetcode][第75题][JAVA][颜色分类][双(三)指针][计数排序]
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
【問題描述】[中等]
【解答思路】
1. 三指針
時間復(fù)雜度:O(N) 空間復(fù)雜度:O(1)
class Solution {public void sortColors(int[] nums) {int n = nums.length;int p0 = 0, p2 = n - 1;for (int i = 0; i <= p2; ++i) {while (i <= p2 && nums[i] == 2) {int temp = nums[i];nums[i] = nums[p2];nums[p2] = temp;--p2;}if (nums[i] == 0) {int temp = nums[i];nums[i] = nums[p0];nums[p0] = temp;++p0;}}} } public void sortColors(int[] nums) {int len= nums.length;int low = 0 ;int high= len-1;int i=0;while(i<=high){if(nums[i]==0){int tmp = nums[i];nums[i] = nums[low];nums[low] =tmp;++i;++low;}else if(nums[i]==1){++i;}else if(i<=high && nums[i]==2){int tmp = nums[i];nums[i] = nums[high];nums[high] =tmp;--high;}}}快排思想理解
import java.util.Arrays;public class Solution {public void sortColors(int[] nums) {int len = nums.length;if (len < 2) {return;}// all in [0, zero) = 0// all in [zero, i) = 1// all in [two, len - 1] = 2// 循環(huán)終止條件是 i == two,那么循環(huán)可以繼續(xù)的條件是 i < two// 為了保證初始化的時候 [0, zero) 為空,設(shè)置 zero = 0,// 所以下面遍歷到 0 的時候,先交換,再加int zero = 0;// 為了保證初始化的時候 [two, len - 1] 為空,設(shè)置 two = len// 所以下面遍歷到 2 的時候,先減,再交換int two = len;int i = 0;// 當(dāng) i == two 上面的三個子區(qū)間正好覆蓋了全部數(shù)組// 因此,循環(huán)可以繼續(xù)的條件是 i < twowhile (i < two) {if (nums[i] == 0) {swap(nums, i, zero);zero++;i++;} else if (nums[i] == 1) {i++;} else {two--;swap(nums, i, two);}}}private void swap(int[] nums, int index1, int index2) {int temp = nums[index1];nums[index1] = nums[index2];nums[index2] = temp;} }作者:liweiwei1419 鏈接:https://leetcode-cn.com/problems/sort-colors/solution/kuai-su-pai-xu-partition-guo-cheng-she-ji-xun-huan/2. 單指針 兩次循環(huán)
時間復(fù)雜度:O(N) 空間復(fù)雜度:O(1)
class Solution {public void sortColors(int[] nums) {int n = nums.length;int ptr = 0;for (int i = 0; i < n; ++i) {if (nums[i] == 0) {int temp = nums[i];nums[i] = nums[ptr];nums[ptr] = temp;++ptr;}}for (int i = ptr; i < n; ++i) {if (nums[i] == 1) {int temp = nums[i];nums[i] = nums[ptr];nums[ptr] = temp;++ptr;}}} }【總結(jié)】
1. 雙指針三指針 有序排序重要思想
2.循環(huán)不變量
轉(zhuǎn)載鏈接:https://leetcode-cn.com/problems/sort-colors/solution/yan-se-fen-lei-by-leetcode-solution/
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的[Leetcode][第75题][JAVA][颜色分类][双(三)指针][计数排序]的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 软件质量保障之代码走查
- 下一篇: 【数据结构与算法】【算法思想】Dijks