返回介绍

solution / 0000-0099 / 0075.Sort Colors / README_EN

发布于 2024-06-17 01:04:40 字数 5450 浏览 0 评论 0 收藏 0

75. Sort Colors

中文文档

Description

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

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

You must solve this problem without using the library's sort function.

 

Example 1:

Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

Example 2:

Input: nums = [2,0,1]
Output: [0,1,2]

 

Constraints:

  • n == nums.length
  • 1 <= n <= 300
  • nums[i] is either 0, 1, or 2.

 

Follow up: Could you come up with a one-pass algorithm using only constant extra space?

Solutions

Solution 1: Three Pointers

We define three pointers $i$, $j$, and $k$. Pointer $i$ is used to point to the rightmost boundary of the elements with a value of $0$ in the array, and pointer $j$ is used to point to the leftmost boundary of the elements with a value of $2$ in the array. Initially, $i=-1$, $j=n$. Pointer $k$ is used to point to the current element being traversed, initially $k=0$.

When $k < j$, we perform the following operations:

  • If $nums[k] = 0$, then swap it with $nums[i+1]$, then increment both $i$ and $k$ by $1$;
  • If $nums[k] = 2$, then swap it with $nums[j-1]$, then decrement $j$ by $1$;
  • If $nums[k] = 1$, then increment $k$ by $1$.

After the traversal, the elements in the array are divided into three parts: $[0,i]$, $[i+1,j-1]$ and $[j,n-1]$.

The time complexity is $O(n)$, where $n$ is the length of the array. Only one traversal of the array is needed. The space complexity is $O(1)$.

class Solution:
  def sortColors(self, nums: List[int]) -> None:
    i, j, k = -1, len(nums), 0
    while k < j:
      if nums[k] == 0:
        i += 1
        nums[i], nums[k] = nums[k], nums[i]
        k += 1
      elif nums[k] == 2:
        j -= 1
        nums[j], nums[k] = nums[k], nums[j]
      else:
        k += 1
class Solution {
  public void sortColors(int[] nums) {
    int i = -1, j = nums.length, k = 0;
    while (k < j) {
      if (nums[k] == 0) {
        swap(nums, ++i, k++);
      } else if (nums[k] == 2) {
        swap(nums, --j, k);
      } else {
        ++k;
      }
    }
  }

  private void swap(int[] nums, int i, int j) {
    int t = nums[i];
    nums[i] = nums[j];
    nums[j] = t;
  }
}
class Solution {
public:
  void sortColors(vector<int>& nums) {
    int i = -1, j = nums.size(), k = 0;
    while (k < j) {
      if (nums[k] == 0) {
        swap(nums[++i], nums[k++]);
      } else if (nums[k] == 2) {
        swap(nums[--j], nums[k]);
      } else {
        ++k;
      }
    }
  }
};
func sortColors(nums []int) {
  i, j, k := -1, len(nums), 0
  for k < j {
    if nums[k] == 0 {
      i++
      nums[i], nums[k] = nums[k], nums[i]
      k++
    } else if nums[k] == 2 {
      j--
      nums[j], nums[k] = nums[k], nums[j]
    } else {
      k++
    }
  }
}
/**
 Do not return anything, modify nums in-place instead.
 */
function sortColors(nums: number[]): void {
  let i = -1;
  let j = nums.length;
  let k = 0;
  while (k < j) {
    if (nums[k] === 0) {
      ++i;
      [nums[i], nums[k]] = [nums[k], nums[i]];
      ++k;
    } else if (nums[k] === 2) {
      --j;
      [nums[j], nums[k]] = [nums[k], nums[j]];
    } else {
      ++k;
    }
  }
}
impl Solution {
  pub fn sort_colors(nums: &mut Vec<i32>) {
    let mut i = -1;
    let mut j = nums.len();
    let mut k = 0;
    while k < j {
      if nums[k] == 0 {
        i += 1;
        nums.swap(i as usize, k as usize);
        k += 1;
      } else if nums[k] == 2 {
        j -= 1;
        nums.swap(j, k);
      } else {
        k += 1;
      }
    }
  }
}
public class Solution {
  public void SortColors(int[] nums) {
    int i = -1, j = nums.Length, k = 0;
    while (k < j) {
      if (nums[k] == 0) {
        swap(nums, ++i, k++);
      } else if (nums[k] == 2) {
        swap(nums, --j, k);
      } else {
        ++k;
      }
    }
  }

  private void swap(int[] nums, int i, int j) {
    int t = nums[i];
    nums[i] = nums[j];
    nums[j] = t;
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文