当前位置:   article > 正文

删除排序数组中的重复数字 II_删除排序数组中文

删除排序数组中文

 删除排序数组中的重复数字 II

跟进“删除重复数字”:

如果可以允许出现两次重复将如何处理?


样例

给出数组A =[1,1,1,2,2,3],你的函数应该返回长度5,此时A=[1,1,2,2,3]

  1. public class Solution {
  2. /**
  3. * @param A: a array of integers
  4. * @return : return an integer
  5. */
  6. public int removeDuplicates(int[] nums) {
  7. // write your code here
  8. if(nums == null || nums.length == 0) return 0;
  9. int reslen = 0;
  10. int j = reslen;
  11. int len = nums.length;
  12. Map<Integer,Integer> times = new HashMap<>();
  13. //int[] times = new int[len]; 有负数的情况
  14. for(int i = 0 ; i < len; i++){
  15. int cou = 0;
  16. if(times.containsKey(nums[i])){
  17. cou = times.get(nums[i]);
  18. }else{
  19. times.put(nums[i],cou);
  20. }
  21. if(cou < 2){
  22. nums[j++] = nums[i];
  23. // times[nums[i]] += 1;
  24. times.put(nums[i], ++cou);
  25. } else{
  26. // times[nums[i]] += 1;
  27. times.put(nums[i], ++cou);
  28. }
  29. }
  30. reslen = j;
  31. return reslen;
  32. }
  33. }


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/blog/article/detail/50616
推荐阅读
相关标签
  

闽ICP备14008679号