题解 | #草原上的牛群#
草原上的牛群
https://www.nowcoder.com/practice/0661aa40ac8e48f4906df7aa24c3db90
知识点
数组
解题思路
当当前nums[i]等于nums[i-1]表示同一个牛群ans加一,同一个牛群设置nums[ans] = nums[i],注意数组要判段长度是否为0。
Java题解
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型一维数组 * @return int整型 */ public int remove_duplicates (int[] nums) { // write code here int n = nums.length; if(n == 0) return 0; int ans = 1; for (int i = 1; i < n; i++){ if(nums[i] != nums[i - 1]) { ans++; } nums[ans] = nums[i]; } return ans; } }