ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

LeetCode 0075 Sort Colors

2022-04-25 07:00:19  阅读:211  来源: 互联网

标签:Sort operations nums int 复杂度 length 快排 Colors 0075


原题传送门

1. 题目描述

2. Solution 1

1、思路分析
类似快排思想,把所有的0放到数组头部,把所有2放到数组尾部,这样1全部留在中间。

2、代码实现

package Q0099.Q0075SortColors;

public class Solution {
    /*
       The idea is to sweep all 0s to the left and all 2s to the right, then all 1s are left in the middle.
       It is hard to define what is a "one-pass" solution but this algorithm is bounded by O(2n),
       meaning that at most each element will be seen and operated twice (in the case of all 0s).
       You may be able to write an algorithm which goes through the list only once,
       but each step requires multiple operations, leading the total operations larger than O(2n).
       类似快排思想
     */
    public void sortColors(int[] nums) {
        if (nums == null || nums.length < 2) return;
        int low = 0, high = nums.length - 1;
        int i = 0;
        while (i <= high) {
            if (nums[i] == 0) {
                exchange(nums, i, low);
                i++;
                low++;
            } else if (nums[i] == 2) {
                exchange(nums, i, high);
                high--;
            } else {
                i++;
            }
        }
    }

    private void exchange(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

3、复杂度分析
时间复杂度: O(n)
空间复杂度: O(1)

标签:Sort,operations,nums,int,复杂度,length,快排,Colors,0075
来源: https://www.cnblogs.com/junstat/p/16188582.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有