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 }
  • 相关阅读:
    @font-face
    闭包
    DOM事件
    DOM属性
    使用谷歌chrome浏览器查看任何标签的固有属性
    chmod命令
    C++笔记之零碎点
    C++学习之 —— 输入输出
    常见素数筛选方法原理和Python实现
    Django的MVT模型
  • 原文地址:https://www.cnblogs.com/zle1992/p/8643531.html
Copyright © 2011-2022 走看看