zoukankan      html  css  js  c++  java
  • LeetCode & Q26-Remove Duplicates from Sorted Array-Easy

    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]
    (问题一发现,在于,题目要求的是改变nums[]的内容,而不是输出一个新的数组)
    (在小本本上记下,要研究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的区别,此处用法很巧妙,也很必要!
  • 相关阅读:
    HDU 5338(ZZX and Permutations-用线段树贪心)
    编程之美-活动中心(三分)
    form的method用get导致中文乱码
    Tomcat: Could not clean server of obsolete files
    Eclipse打开javadoc框
    Java EE各种documentation
    web-project的/WEB-INF/lib
    在jsp里面不要瞎用<!-- -->注释
    [流水账]搜索与web-container版本匹配的jar包
    session的创建与销毁
  • 原文地址:https://www.cnblogs.com/duyue6002/p/7141716.html
Copyright © 2011-2022 走看看