• 技术文章 >Java >java教程

    LeetCode & Q26-Remove Duplicates from Sorted Array-Easy

    PHP中文网PHP中文网2017-07-09 18:12:13原创865

    Descriptions:

    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.

    我写的一直有问题...用了HashSet集合,没有研究过这个类型,[1,1,2]输出结果一直是[1,1]

    (在小本本上记下,要研究HashSet)

    import java.util.HashSet;
    
    import java.util.Set;
    
    public class Solution {
    
        public static int removeDuplicates(int[] nums) {
    
            Set<Integer> tempSet = new HashSet<>();
    
            for(int i = 0; i < nums.length; i++) {
    
                Integer wrap = Integer.valueOf(nums[i]);
    
                tempSet.add(wrap);
    
            }
    
            return tempSet.size();
    
        }
    
    }

    下面是优秀答案

    Solutions:

    public class Solution {
    
        public static int removeDuplicates(int[] nums) {
    
            int j = 0;
    
            for(int i = 0; i < nums.length; i++) {
    
                if(nums[i] != nums[j]) {
    
                    nums[++j] = nums[i];
    
                }
    
            }
    
            return ++j;
    
        }
    
    }

    有两个点需要注意:

    1. 因为重复的可能有多个,所以不能以相等来做判定条件
    2. 注意j++++j的区别,此处用法很巧妙,也很必要!

    以上就是LeetCode &amp; Q26-Remove Duplicates from Sorted Array-Easy的详细内容,更多请关注php中文网其它相关文章!

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    上一篇:JSP基础入门 下一篇:自己动手写 PHP MVC 框架(40节精讲/巨细/新人进阶必看)

    相关文章推荐

    • Java数据结构常见排序算法(总结分享)• 一文详解怎么实现微服务鉴权• Java中Map集合体系的基本使用和常用API• 一起来分析java设计模式之单例• 一文搞懂Java线程池实现原理
    1/1

    PHP中文网