zoukankan      html  css  js  c++  java
  • leetcode 26 Remove Duplicates from Sorted Array

      题目大意:

      数组经过排序,删除数组中的元素,使数组中所有元素只出现一次,返回新数组的长度。不允许分配新的数组空间。

      解法一(没看到题目中的数组已经排好序了。。。):

      

    public class Solution {
        public int removeDuplicates(int[] nums) {
            
            boolean flag = true;
            int res = 0;
            
            for(int i = 0; i < nums.length; i++)
            {
                
                for(int j = res-1; j >= 0; j--)
                {
                    if(nums[j] == nums[i])
                    flag = false;
                }
                
                if(flag == true)
                {
                    nums[res++] = nums[i];
                }
                flag = true;
            }
            
            return res;
        }
    }

    解法二(因为已经排好序了,所以,直接判断相邻的两个元素是否相同即可):

    public class Solution {
        public int removeDuplicates(int[] nums) {
            
            int i = 0,res = 0;
            while(i < nums.length)
            {
                while(i+1 < nums.length && nums[i] == nums[i+1]) i++;
                
                nums[res++] = nums[i];
                i++;
            }
            
            return res;
        }
    }
  • 相关阅读:
    css3基础篇二
    css3基础篇一
    react基础篇六
    react基础篇五
    react基础篇四
    react基础篇三
    react基础篇二
    react基础篇一
    矩阵
    POJ 3071 Football
  • 原文地址:https://www.cnblogs.com/zyqBlog/p/5989923.html
Copyright © 2011-2022 走看看