zoukankan      html  css  js  c++  java
  • 26. Remove Duplicates from Sorted Array(删除排序数组中的重复元素,利用排序的特性,比较大小)

     

    Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new length.

    Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

    Example:

    Given nums = [1,1,2],
    
    Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
    It doesn't matter what you leave beyond the new length.
    
     1 class Solution {
     2 public:
     3     int removeDuplicates(vector<int>& a) {
     4         if(a.size()==0) return 0;
     5         int i = 0;
     6         int j = 1;
     7 
     8         for (;j < a.size();++j) {
     9             if(a[i]!=a[j]) {
    10                 i++;
    11             }
    12             a[i] = a[j];
    13         }
    14         return i+1;
    15     }
    16 };

     与删除排序链表中的重复元素类似,利用排序的特性,如果后一个元素大于当前元素,则不是重复的数字

     1 class Solution:
     2     def removeDuplicates(self, nums):
     3         """
     4         :type nums: List[int]
     5         :rtype: int
     6         """
     7         if len(nums)< 2:
     8             return len(nums)
     9         j = 0
    10         for i in range(1,len(nums)):
    11             if(nums[i]>nums[j]):
    12                 j+=1
    13                 nums[j]=nums[i]
    14 
    15         return j+1

    20180507

     1 class Solution {
     2     public int removeDuplicates(int[] nums) {
     3         int m = 0;
     4         for(int i = 0;i<nums.length;i++){
     5             if(m<1||nums[i]>nums[m-1])
     6                 nums[m++] = nums[i];
     7         }
     8         return m;
     9     }
    10 }
  • 相关阅读:
    JS判断对象中是否存在某参数
    JS通过url下载文件
    .NET CORE LinQ查询中计算时间差
    C# 判断某个时间是星期几
    C#数组去重
    python Tank
    kubeflannel.yml Tank
    片言只语 Tank
    other Tank
    ERROR大集合 Tank
  • 原文地址:https://www.cnblogs.com/zle1992/p/8643531.html
Copyright © 2011-2022 走看看