Leetcode - Remove Duplicates from Sorted Array
来源:互联网 发布:阿sa长相 知乎 编辑:程序博客网 时间:2024/06/04 01:07
Question
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.
Java Code
public int removeDuplicates(int[] nums) { final int n = nums.length; if(n == 0) return 0; if(n == 1) return 1; int i = 0;//指针i指向当前不重复子数组末位的下一位 int j = 1;//指针j用于遍历数组元素 //遍历数组起始的无重复元素区间 while(nums[i++] != nums[j++]) { if(j == n) return n; } while(j < n) { if(j == n-1) {//如果已遍历到数组末尾,则判断最后两个元素是否相同 if(nums[i] != nums[j]) { nums[i] = nums[j]; return i+1; } else return i; } if(nums[i] != nums[j]) {//两个元素值不相等则用j指针对应的值覆盖i指针对应的值 while(nums[j] == nums[j + 1]) {//与nums[j]相等的元素可能有多个,找到最后一个 if(j == n-2) { nums[i] = nums[j]; return i+1; } j++; } nums[i++] = nums[j++]; }else//两个元素值相等则使j指针一直跳过重复的元素 j++; } return i;}
说明
- 本题算是另一题的加强版,基本解题思路差不多,但不同的是,本题的重复元素可能不止一个数值,所以需要仔细分析两个指针之间的关系,还有需要注意的一点就是不要让指针j越界
更新
2016.04.27
public int removeDuplicates2(int[] nums) { int n = nums.length; if(n == 0) return 0; int i = 0;//用于指向当前无重复元素子数组的下一位 int j = 0;//用于遍历nums数组的元素 //遍历数组起始的无重复元素区间 while(nums[i++] != nums[j++]) { if(i == n) return n; } while(j < nums.length) { if(nums[j] == nums[j - 1])//如果相邻元素的值相等,则继续遍历 j++; else//否则,用j指针对应的值覆盖i指针对应的值,再继续遍历 nums[i++] = nums[j++]; } //返回无重复元素子数组的最大长度 return i;}
0 0
- [leetcode][array] Remove Duplicates from Sorted Array
- 【Leetcode】【Array】Remove Duplicates from Sorted Array
- LeetCode: Remove Duplicates from Sorted Array
- LeetCode: Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array
- [Leetcode] Remove Duplicates from Sorted Array II
- LeetCode: Remove Duplicates from Sorted Array
- LeetCode: Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array II
- leetcode 35: Remove Duplicates from Sorted Array
- [LeetCode] Remove Duplicates from Sorted Array II
- [LeetCode] Remove Duplicates from Sorted Array
- Leetcode: Remove Duplicates from Sorted Array
- [leetcode] Remove Duplicates from Sorted Array II
- [LeetCode]Remove Duplicates from Sorted Array
- [LeetCode]Remove Duplicates from Sorted Array II
- [leetcode]Remove Duplicates from Sorted Array
- [leetcode]Remove Duplicates from Sorted Array II
- 日语特殊符号
- leetcode_121 Best Time to Buy and Sell Stock
- 毕业设计(一)——基于深度学习的一类图像共性特征提取 (caffe)
- Base64转成图片 损坏的问题
- C++ 中 delete 和 delete[] 的区别?
- Leetcode - Remove Duplicates from Sorted Array
- 让Select的option支持双击事件
- JSP九大内置对象详解(二)
- android基础知识整理(1)
- Codeforces 630N Forecast
- 笔试题目总结之一——TCP/IP协议栈
- PointPlay(document.getElementById('selectForPlay').value);
- 懒得加载jquery
- 【分步详解】两个有序数组中的中位数和Top K问题