博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode — remove-duplicates-from-sorted-array
阅读量:6881 次
发布时间:2019-06-27

本文共 1423 字,大约阅读时间需要 4 分钟。

import java.util.Arrays;/** * Source : https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array/ * * Created by lverpeng on 2017/7/12. * * 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 A = [1,1,2], * * Your function should return length = 2, and A is now [1,2]. */public class RemoveDuplicates {    /**     *     * 因为是有序的,所以如果有重复的元素一定是相邻的,只要判断相邻的不相等的个数就知道不重复的元素个数     *     * @param num     * @return     */    public int remove (int[] num) {        int pos = 0;        for (int i = 0; i < num.length - 1; i++) {            if (num[i] != num[i + 1]) {                num[pos] = num[i];                pos++;            }        }        System.out.println(Arrays.toString(num));        // 另外加上最后一个元素        return pos + 1;    }    public static void main(String[] args) {        RemoveDuplicates removeDuplicates = new RemoveDuplicates();        int[] arr = new int[]{1,1,2};        int[] arr1 = new int[]{1,1,1,2};        int[] arr2 = new int[]{1,1,22,22,22,33};        System.out.println(removeDuplicates.remove(arr));        System.out.println(removeDuplicates.remove(arr1));        System.out.println(removeDuplicates.remove(arr2));    }}

转载于:https://www.cnblogs.com/sunshine-2015/p/7406757.html

你可能感兴趣的文章
WCF 入门之旅(3): 怎样测试WCF服务是否正常运行
查看>>
连接ftp服务器 JDK 1.7
查看>>
Java获取本机IP
查看>>
easyUIDataGrid对象返回值
查看>>
侧滑面板(对viewGroup的自定义)
查看>>
Objective-C Data Encapsulation
查看>>
NUC1474 Ants【水题】
查看>>
POJ NOI MATH-7831 计算星期几
查看>>
ubuntu中KDE与GNOME安装切换
查看>>
svn的使用详解
查看>>
Android带参数链接请求服务器
查看>>
AbisPlat框架介绍
查看>>
什么样的男人能轻松泡到妞?
查看>>
No package nginx available. |一次解决一个问题
查看>>
JavaScript高级程序设计:第十七章
查看>>
springboot~mogodb多条件拼接
查看>>
poj 1488 TEX Quotes 双引号的改写 (☆☆☆☆☆)
查看>>
C# 生成windows 服务打包程序
查看>>
Python3实现QQ机器人自动爬取百度文库的搜索结果并发送给好友(主要是爬虫)...
查看>>
线程池代码(通用版)
查看>>