题解 | #草原牛群集合#
草原牛群集合
https://www.nowcoder.com/practice/6fc74519ff9c44288dbcec5db7345ded
知识点
数组
解题思路
用ans保存与val相同的个数,再在原数组上修改数组,当val与nums[i]相同的时候,ans加一,不相同时把当前数放到nums[i - ans]位置上。
Java题解
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型一维数组
* @param val int整型
* @return int整型
*/
public int remove_cows (int[] nums, int val) {
// write code here
int ans = 0;
for (int i = 0; i < nums.length; i++){
if(nums[i] == val){
ans ++;
} else {
nums[i - ans] = nums[i];
}
}
return nums.length - ans;
}
}

查看16道真题和解析