zoukankan      html  css  js  c++  java
  • remove duplicate of the sorted array

    description:

    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 in place with constant memory.

    For example,
    Given input array 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.

    thoughts:

    first we should juage if the array is empty, if true, we can just return length=0,and do not do anything special about the array.if not, then the length must >=1.we first record the nums[0]  as temp and  legnth = 1, then find the first different number with it,make the temp equal to it, and length++;end make the nums[length -1] = temp.do this operation untill you have scan all the value of the nums,then return length.

    my code in java

    package easy;
    
    public class RemoveDuplicatesOfSortedArray {
        
        public int removeDuplicates(int[] nums){
            //if the nums is empty return length = 0
            int length = 0;
            if(nums.length>0){
                int temp = nums[0];
                length=1;
                for(int i = 0; i<nums.length;i++){
                    if(temp != nums[i]){
                        //找到所有不一样的数
                        temp = nums[i];
                        length++;
                        //将所有不一样的数放在相应的位置
                        nums[length - 1] = temp;
                    }
                }
            }
            
            return length;
        }
        
        public static void main(String[] args){
            RemoveDuplicatesOfSortedArray a = new RemoveDuplicatesOfSortedArray();
            int[] nums = new int[]{1,1,2};
            int length = a.removeDuplicates(nums);
            System.out.println(length);
        }
    
    }
  • 相关阅读:
    pcb过孔盖油
    stm32的串口中断
    串口速度计算
    块元素、行内元素、行内块元素及其相互转化
    CSS伪类选择器
    CSS后代选择器、子代选择器
    CSS表示颜色、行间距、缩进、文字修饰
    CSS学习之通配符选择器
    【DP专题】——洛谷P0170道路游戏
    ssh框架jar包下载地址
  • 原文地址:https://www.cnblogs.com/whatyouknow123/p/7488162.html
Copyright © 2011-2022 走看看