题解 | #草原上的牛群分布#
草原上的牛群分布
https://www.nowcoder.com/practice/25752634aa444758843eed6ff227703a
知识点
数组,指针
解题思路
使用map来存放每个数出现的次数,location表示下一次元素放的位置下标。
在循环中如果当前数出现的次数小于3,首先更新map,再把该数放到location的位置,ans也要加一;如果出现次数大于3了,就不做任何操作。
Java题解
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型一维数组 * @return int整型 */ public int remove_duplicates_v3 (int[] nums) { // write code here int n = nums.length; Map<Integer,Integer> map = new HashMap<>(); int location = 0,ans = 0; for (int num : nums) { int cowNum = map.getOrDefault(num,0); if(cowNum < 3){ map.put(num,cowNum + 1); nums[location ++] = num; ans++; } } return ans; } }