26. Remove Duplicates from Sorted Array

Easy

Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory.

Example 1:

Given 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 returned length.

Example 2:

Given nums = [0,0,1,1,1,2,2,3,3,4],

Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.

It doesn't matter what values are set beyond the returned length.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums); // any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
    print(nums[i]);
}
package leetcode.easy;

public class RemoveDuplicatesFromSortedArray {
@org.junit.Test
public void test() {
int[] nums1 = { 1, 1, 2 };
int[] nums2 = { 0, 0, 1, 1, 1, 2, 2, 3, 3, 4 };
System.out.println(removeDuplicates(nums1));
System.out.println(removeDuplicates(nums2));
} public int removeDuplicates(int[] nums) {
if (nums.length == 0) {
return 0;
}
int i = 0;
for (int j = 1; j < nums.length; j++) {
if (nums[j] != nums[i]) {
i++;
nums[i] = nums[j];
}
}
return i + 1;
}
}

最新文章

  1. 带你玩转Visual Studio
  2. C# 利用反射
  3. HTMl链接- target/ name
  4. Coursera Robotics系列课心得
  5. 试用VSCode
  6. 从零开始--系统深入学习IOS(使用Swift---带链接)
  7. 帮助你在 Photoshop 中轻松实现长阴影效果的工具
  8. php面试题之二——数据结构和算法(高级部分)
  9. 如何处理ABBYY中出现错误代码142和55的问题
  10. 构建ASP.NET MVC5+EF6+EasyUI 1.4.3+Unity4.x注入的后台管理系统
  11. Turn the corner--hdu2438(3分法)
  12. QT5中的pro文件中为何要加入&quot;QT += widgets&quot;
  13. Spring Cloud在国内中小型公司能用起来吗?
  14. 基于am3358的led跑马灯测试
  15. Spring知识点回顾(06)Profile 和 条件注解 @Conditional
  16. Krajee插件的用法
  17. css+js调整当前界面背景音量
  18. [原创]基于SpringAOP开发的方法调用链分析框架
  19. 前端bug记录
  20. 解决samtools报错:[main_samview] region &quot;chr2:20,100,000-20,200,000&quot; specifies an unknown reference name. Continue anyway.

热门文章

  1. Parameter 0 of method redisTemplate in org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration required a bean of type &#39;org.springframework.data.redis.connection.RedisConnectionFactor
  2. 基于pg_qualstats和hypopg的自动索引调优
  3. 第119题:杨辉三角II
  4. waitgroup等待退出
  5. javascript权威指南第22章高级技巧
  6. NodeJS基础知识
  7. PHP全栈学习笔记27
  8. kaptcha 配置
  9. 在Spring中读取properties文件
  10. 去掉 webstorm 灰色的数据类型提示