java 数组去掉重复元素

该文章介绍了一个编程问题,要求在给定非降序整数数组中删除重复元素,保持原始顺序,并返回唯一元素的数量。Solution类提供了实现这一功能的方法,通过异或操作检测并替换重复值,最后返回不重复元素的新数组大小。
摘要由CSDN通过智能技术生成

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums.

Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things:

  • Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums.
  • Return k.
class Solution {
    public int removeDuplicates(int[] nums) {
        if(nums.length==0)
          return 0;
        if(nums.length==1)
          return 1;
      
        int itter = 0;int k = 0;
        for(int i = 1;i<nums.length;i++){
            if(i==nums.length-1){
               int res = nums[i]^nums[itter];
            if(res==0){
             nums[i] = Integer.MAX_VALUE;
            } 

                itter++;
                i = itter+1;
                if(itter==nums.length-1)
                 break;
                if(nums[itter]==Integer.MAX_VALUE){
                    itter++;
                    i = itter+1;
                    if(itter==nums.length-1)
                      break;
                }

            }
            int res = nums[i]^nums[itter];
            if(res==0){
             nums[i] = Integer.MAX_VALUE;
            }
        }
        int []tmp = new int[nums.length];
        int j = 0;
        for(int i = 0;i<nums.length;i++){
            if(nums[i]!=Integer.MAX_VALUE)
                tmp[j++] = nums[i];
        }
    int size = 0;
    for(int i = 0;i<j;i++){
        nums[i] = tmp[i];
        size++;
    }

    return size;

    }
}
  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值