【算法】2149. 按符号重排数组(多语言实现)

105 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第6天,点击查看活动详情


2149. 按符号重排数组:

给你一个下标从 0 开始的整数数组 nums ,数组长度为 偶数 ,由数目相等的正整数和负整数组成。

你需要 重排 nums 中的元素,使修改后的数组满足下述条件:

  1. 任意 连续 的两个整数 符号相反
  2. 对于符号相同的所有整数,保留 它们在 nums 中的 顺序
  3. 重排后数组以正整数开头。

重排元素满足上述条件后,返回修改后的数组。

样例 1:

输入:
	nums = [3,1,-2,-5,2,-4]
	
输出:
	[3,-2,1,-5,2,-4]
	
解释:
	nums 中的正整数是 [3,1,2] ,负整数是 [-2,-5,-4] 。
	重排的唯一可行方案是 [3,-2,1,-5,2,-4],能满足所有条件。
	像 [1,-2,2,-5,3,-4][3,1,2,-2,-5,-4][-2,3,-5,1,-4,2] 这样的其他方案是不正确的,因为不满足一个或者多个条件。 

样例 2:

输入:
	nums = [-1,1]
	
输出:
	[1,-1]
	
解释:
	1 是 nums 中唯一一个正整数,-1 是 nums 中唯一一个负整数。
	所以 nums 重排为 [1,-1]

提示:

  • 2 <= nums.length <= 2 * 105
  • nums.length 是 偶数
  • 1 <= |nums[i]| <= 105
  • nums 由 相等 数量的正整数和负整数组成

分析

  • 面对这道算法题目,二当家的陷入了沉思。
  • 先将原数组直接按照正负数拆分成两部分,再拼接是比较简单的方式。
  • 使用双指针在时间复杂度上比较合适,双指针本身也有两种方式:一种是记录遍历到原数组的下标;另外一种也可以记录生成结果的下标。
  • 还有一个思考的方向是能否原地生成,不去开辟新的空间。

题解

rust

impl Solution {
    pub fn rearrange_array(nums: Vec<i32>) -> Vec<i32> {
        let mut ans = vec![0; nums.len()];
        let mut positiveIndex = 0;
        let mut negativeIndex = 1;

        nums.iter().for_each(|&n| {
            if n > 0 {
                ans[positiveIndex] = n;
                positiveIndex += 2;
            } else {
                ans[negativeIndex] = n;
                negativeIndex += 2;
            }
        });

        ans
    }
}

go

func rearrangeArray(nums []int) []int {
    ans := make([]int, len(nums))
    positiveIndex, negativeIndex := 0, 1
    for _, n := range nums {
        if n > 0 {
            ans[positiveIndex] = n
            positiveIndex += 2
        } else {
            ans[negativeIndex] = n
            negativeIndex += 2
        }
    }
    return ans
}

typescript

function rearrangeArray(nums: number[]): number[] {
    const ans = new Array(nums.length);
    let positiveIndex = 0;
    let negativeIndex = 1;
    for (const n of nums) {
        if (n > 0) {
            ans[positiveIndex] = n;
            positiveIndex += 2;
        } else {
            ans[negativeIndex] = n;
            negativeIndex += 2;
        }
    }
    return ans;
};

c

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* rearrangeArray(int* nums, int numsSize, int* returnSize){
    int *ans = malloc(numsSize * sizeof(int));
    *returnSize = numsSize;
    int positiveIndex = 0, negativeIndex = 1;
    for (int i = 0; i < numsSize; ++i) {
        int n = nums[i];
        if (n > 0) {
            ans[positiveIndex] = n;
            positiveIndex += 2;
        } else {
            ans[negativeIndex] = n;
            negativeIndex += 2;
        }
    }
    return ans;
}

c++

class Solution {
public:
    vector<int> rearrangeArray(vector<int>& nums) {
        vector<int> ans(nums.size());
        int positiveIndex = 0, negativeIndex = 1;
        for (int &n: nums) {
            if (n > 0) {
                ans[positiveIndex] = n;
                positiveIndex += 2;
            } else {
                ans[negativeIndex] = n;
                negativeIndex += 2;
            }
        }
        return ans;
    }
};

python

class Solution:
    def rearrangeArray(self, nums: List[int]) -> List[int]:
        ans = [0] * len(nums)
        positive_index, negative_index = 0, 1
        for n in nums:
            if n > 0:
                ans[positive_index] = n
                positive_index += 2
            else:
                ans[negative_index] = n
                negative_index += 2
        return ans


java

class Solution {
    public int[] rearrangeArray(int[] nums) {
        int[] ans           = new int[nums.length];
        int   positiveIndex = 0, negativeIndex = 1;
        for (int n : nums) {
            if (n > 0) {
                ans[positiveIndex] = n;
                positiveIndex += 2;
            } else {
                ans[negativeIndex] = n;
                negativeIndex += 2;
            }
        }
        return ans;
    }
}

原题传送门:https://leetcode.cn/problems/rearrange-array-elements-by-sign/


非常感谢你阅读本文~
放弃不难,但坚持一定很酷~
希望我们大家都能每天进步一点点~
本文由 二当家的白帽子:https://juejin.cn/user/2771185768884824/posts 博客原创~