返回介绍

solution / 2400-2499 / 2459.Sort Array by Moving Items to Empty Space / README_EN

发布于 2024-06-17 01:03:05 字数 5888 浏览 0 评论 0 收藏 0

2459. Sort Array by Moving Items to Empty Space

中文文档

Description

You are given an integer array nums of size n containing each element from 0 to n - 1 (inclusive). Each of the elements from 1 to n - 1 represents an item, and the element 0 represents an empty space.

In one operation, you can move any item to the empty space. nums is considered to be sorted if the numbers of all the items are in ascending order and the empty space is either at the beginning or at the end of the array.

For example, if n = 4, nums is sorted if:

  • nums = [0,1,2,3] or
  • nums = [1,2,3,0]

...and considered to be unsorted otherwise.

Return _the minimum number of operations needed to sort _nums.

 

Example 1:

Input: nums = [4,2,0,3,1]
Output: 3
Explanation:
- Move item 2 to the empty space. Now, nums = [4,0,2,3,1].
- Move item 1 to the empty space. Now, nums = [4,1,2,3,0].
- Move item 4 to the empty space. Now, nums = [0,1,2,3,4].
It can be proven that 3 is the minimum number of operations needed.

Example 2:

Input: nums = [1,2,3,4,0]
Output: 0
Explanation: nums is already sorted so return 0.

Example 3:

Input: nums = [1,0,2,4,3]
Output: 2
Explanation:
- Move item 2 to the empty space. Now, nums = [1,2,0,4,3].
- Move item 3 to the empty space. Now, nums = [1,2,3,4,0].
It can be proven that 2 is the minimum number of operations needed.

 

Constraints:

  • n == nums.length
  • 2 <= n <= 105
  • 0 <= nums[i] < n
  • All the values of nums are unique.

Solutions

Solution 1: Permutation Cycle

For a permutation cycle of length $m$, if $0$ is in the cycle, the number of swaps is $m-1$; otherwise, the number of swaps is $m+1$.

We find all permutation cycles, first calculate the total number of swaps assuming each cycle requires $m+1$ swaps, then check if $0$ is misplaced. If it is, it means $0$ is in a permutation cycle, so we subtract $2$ from the total number of swaps.

Here, $0$ can be at position $0$ or at position $n-1$. We take the minimum of these two cases.

The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array.

class Solution:
  def sortArray(self, nums: List[int]) -> int:
    def f(nums, k):
      vis = [False] * n
      cnt = 0
      for i, v in enumerate(nums):
        if i == v or vis[i]:
          continue
        cnt += 1
        j = i
        while not vis[j]:
          vis[j] = True
          cnt += 1
          j = nums[j]
      return cnt - 2 * (nums[k] != k)

    n = len(nums)
    a = f(nums, 0)
    b = f([(v - 1 + n) % n for v in nums], n - 1)
    return min(a, b)
class Solution {
  public int sortArray(int[] nums) {
    int n = nums.length;
    int[] arr = new int[n];
    for (int i = 0; i < n; ++i) {
      arr[i] = (nums[i] - 1 + n) % n;
    }
    int a = f(nums, 0);
    int b = f(arr, n - 1);
    return Math.min(a, b);
  }

  private int f(int[] nums, int k) {
    boolean[] vis = new boolean[nums.length];
    int cnt = 0;
    for (int i = 0; i < nums.length; ++i) {
      if (i == nums[i] || vis[i]) {
        continue;
      }
      ++cnt;
      int j = nums[i];
      while (!vis[j]) {
        vis[j] = true;
        ++cnt;
        j = nums[j];
      }
    }
    if (nums[k] != k) {
      cnt -= 2;
    }
    return cnt;
  }
}
class Solution {
public:
  int sortArray(vector<int>& nums) {
    int n = nums.size();
    auto f = [&](vector<int>& nums, int k) {
      vector<bool> vis(n);
      int cnt = 0;
      for (int i = 0; i < n; ++i) {
        if (i == nums[i] || vis[i]) continue;
        int j = i;
        ++cnt;
        while (!vis[j]) {
          vis[j] = true;
          ++cnt;
          j = nums[j];
        }
      }
      if (nums[k] != k) cnt -= 2;
      return cnt;
    };

    int a = f(nums, 0);
    vector<int> arr = nums;
    for (int& v : arr) v = (v - 1 + n) % n;
    int b = f(arr, n - 1);
    return min(a, b);
  }
};
func sortArray(nums []int) int {
  n := len(nums)
  f := func(nums []int, k int) int {
    vis := make([]bool, n)
    cnt := 0
    for i, v := range nums {
      if i == v || vis[i] {
        continue
      }
      cnt++
      j := i
      for !vis[j] {
        vis[j] = true
        cnt++
        j = nums[j]
      }
    }
    if nums[k] != k {
      cnt -= 2
    }
    return cnt
  }
  a := f(nums, 0)
  arr := make([]int, n)
  for i, v := range nums {
    arr[i] = (v - 1 + n) % n
  }
  b := f(arr, n-1)
  return min(a, b)
}

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

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

发布评论

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