Leetcode # 75 Sort Colors

来源:互联网 发布:java redis缓存数据库 编辑:程序博客网 时间:2024/05/22 00:48

Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

Note:

You are not suppose to use the library's sort function for this problem.

Difficulty:Medium

写(套)一个冒泡排序(模板)就通过了。

void sortColors(vector<int>& nums) {        int inner = 0, outer = 0;      int median = 0;      int flag = 1;      int length = nums.size();    if(length==0)          return;        for(outer = length-1; outer >= 1 && flag; outer --){          flag = 0;            for(inner = 0; inner < outer; inner ++){              if(nums[inner] > nums[inner + 1]){                  median = nums[inner];                  nums[inner] = nums[inner + 1];                  nums[inner + 1] = median;                    if(flag == 0)                      flag = 1;              }          }      }    return;    }



0 0
原创粉丝点击