【问题标题】:26. Remove Duplicates from Sorted Array - Java26. 从有序数组中删除重复项 - Java
【发布时间】:2021-03-02 07:44:55
【问题描述】:

问题:给定一个排序数组 nums,就地删除重复项,使每个元素只出现一次并返回新的长度。

不要为另一个数组分配额外的空间,您必须通过使用 O(1) 额外内存就地修改输入数组来做到这一点。

public int removeDuplicates(int[] nums) {
if (nums.length == 0) return 0;
int i = 0;
for (int j = 1; j < nums.length; j++) {
    if (nums[j] != nums[i]) {
        i++;
        nums[i] = nums[j];
    }
}
return i + 1;

}

return 语句在这里具体做了什么。 return i + 1 在这里是什么意思?

【问题讨论】:

    标签: java return


    【解决方案1】:

    return i + 1 返回有多少个唯一整数。我相信这是一个 Leetcode 问题,因为它已经到位,int[] 是通过引用传递的,Leetcode 想知道要检查多少个数字(你应该把唯一的数字放在第一个 i + 1 点)。

    如果你看这个问题,它会说: 这意味着您返回数组的长度。

    因此,如果您有数组[1,1,2,3,4,4],您可以将其转换为[1,2,3,4,...],其中... 是数组的其余部分。但是,您返回 4,因为新数组的长度应该是 4

    希望这能为您解决问题!

    【讨论】:

      【解决方案2】:

      您的问题已经回答here;除此之外,我们还可以从零开始,去掉第一个if语句:

      使用b.java 文件进行测试:

      import java.util.*;
      
      class Solution {
          public static final int removeDuplicates(
              final int[] nums
          ) {
      
              int i = 0;
      
              for (int num : nums)
                  if (i == 0 || num > nums[i - 1]) {
                      nums[i++] = num;
                  }
      
              return i;
          }
      }
      
      
      class b {
          public static void main(String[] args) {
              System.out.println(new Solution().removeDuplicates(new int[] { 1, 1, 2}));
              System.out.println(new Solution().removeDuplicates(new int[] { 0, 0, 1, 1, 1, 2, 2, 3, 3, 4}));
          }
      }
      

      打印

      2
      5
      

      【讨论】:

        【解决方案3】:
        • 我尝试过这种简单的方法。这里时间复杂度是 O(n) 和空间 复杂度:O(1)。

              static int removeDuplicates(int[] nums){
              if(nums.length == 0) {
                  return 0;
              }
              int value = nums[0];
              int lastIndex = 0;
              int count = 1;
              for (int i = 1; i < nums.length; i++) {
                  if(nums[i] > value) {
                      value = nums[i];
                      lastIndex = lastIndex+1;
                      nums[lastIndex] = value;
                      count++;
                  }
              }
              return count;
            }
          

        【讨论】:

          猜你喜欢
          • 2012-04-20
          • 2014-04-16
          • 2016-10-01
          • 2017-07-30
          • 2014-04-23
          • 2011-06-29
          • 2021-11-12
          • 2021-01-27
          相关资源
          最近更新 更多