题解 | #草原上的牛群分布#
草原上的牛群分布
https://www.nowcoder.com/practice/25752634aa444758843eed6ff227703a
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型一维数组 * @return int整型 */ public int remove_duplicates_v3 (int[] nums) { // write code here if (nums.length == 0) { return 0; } int i = 0; // 指向数组中当前牛群位置 int count = 1; // 当前位置上的牛群数量 for (int j = 1; j < nums.length; j++) { if (nums[j] == nums[j - 1]) { // 如果当前位置与前一个位置相同 if (count < 3) { // 如果当前位置上的牛群数量未满 3 头,则将牛群移动到数组中 nums[++i] = nums[j]; count++; } } else { // 如果当前位置与前一个位置不相同 // 将牛群移动到数组中,并重置计数器 nums[++i] = nums[j]; count = 1; } } // 返回重新分布的数组长度 return i + 1; } }
知识点:
双指针
文字分析:
用双指针的方法,详解在代码注释中。
复杂度分析:该算法只对数组进行一次遍历,因此时间复杂度为 O(n),其中 n 是数组的长度。算法只使用了常数个额外变量,空间复杂度为 O(1)。
编程语言:
java