题解 | #草原上的牛群#
草原上的牛群
https://www.nowcoder.com/practice/0661aa40ac8e48f4906df7aa24c3db90
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型一维数组 * @return int整型 */ public int remove_duplicates (int[] nums) { // write code here int[] cnt = new int[201]; for(int num : nums) cnt[num]++; int ans = 0; for (int c : cnt) { if (c > 0) ans++; } return ans; } }
- 根据题意,数组元素的取值范围是确定的([0,200]),所以可以定义一个长度为 201 的数组 cnt 用做计数器
- 遍历原数组 nums,利用 cnt 记录每个位置上牛群的个数
- 定义一个 ans,记录返回结果
- 遍历计数器数组 cnt,计数数值大于0的,就是一个有效位置,则ans++
- 返回ans
线性表基础 文章被收录于专栏
链表、递归、栈