75. leetcode Sort Colors

来源:互联网 发布:linux复制文件和文件夹 编辑:程序博客网 时间:2024/06/08 16:17

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.

java

class Solution {    public void sortColors(int[] nums) {        if (nums == null || nums.length == 0 || nums.length == 1) {            return;        }        int left = 0;        int right = nums.length - 1;        int i = 0;        while (i <= right && left <= right) {            if (nums[i] == 1) {                i++;            } else if (nums[i] == 0) {                swap(nums, i, left);                i++;                left++;            } else {                swap(nums, i, right);                right--;            }        }    }    private void swap(int[] nums, int start, int end) {        int temp = nums[start];        nums[start] = nums[end];        nums[end] = temp;    }}

python

class Solution(object):    def sortColors(self, nums):        """        :type nums: List[int]        :rtype: void Do not return anything, modify nums in-place instead.        """        if nums is None or len(nums) == 0 or len(nums) == 1:            return        left, right, i = 0, len(nums) - 1, 0        while i <= right:            if nums[i] == 1:                i += 1            elif nums[i] == 0:                nums[i], nums[left] = nums[left], nums[i]                i, left = i + 1, left + 1            else:                nums[i], nums[right] = nums[right], nums[i]                right -= 1        


原创粉丝点击