26 Remove Duplicates from Sorted Array
2015-08-16 17:17
288 查看
题目链接:https://leetcode.com/problems/remove-duplicates-from-sorted-array/
题目:
解题思路:
使用两个指针 i (指向有序且无重复的序列的最后一位数字)和 j (指向 i 指针之后的元素)
i 初始为 0,j 初始为 1
在 j 小于数组最大下标的前提下,比较 i 和 j 所指元素是否相等
相等,则执行 j ++ 操作。重复执行该过程,直到 i 和 j 所指元素不等为止
不相等,则将 j 当前所指元素复制到 i 所指元素的后继位置
直到 j 的大小等于数组长度时,退出外部大循环
此时,新数组的长度为 i + 1
注意:
比较 i 和 j 所指元素是否相等之前,必须先判断 j 的大小是否已超出数组范围
题目:
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.
解题思路:
使用两个指针 i (指向有序且无重复的序列的最后一位数字)和 j (指向 i 指针之后的元素)
i 初始为 0,j 初始为 1
在 j 小于数组最大下标的前提下,比较 i 和 j 所指元素是否相等
相等,则执行 j ++ 操作。重复执行该过程,直到 i 和 j 所指元素不等为止
不相等,则将 j 当前所指元素复制到 i 所指元素的后继位置
直到 j 的大小等于数组长度时,退出外部大循环
此时,新数组的长度为 i + 1
注意:
比较 i 和 j 所指元素是否相等之前,必须先判断 j 的大小是否已超出数组范围
public class Solution { public int removeDuplicates(int[] nums) { if(nums == null || nums.length == 0) return 0; int len = nums.length; int i = 0; int j = 1; while(j < len) { while(j < len && nums[j] == nums[i]) j ++; if(j == len) break; nums[++ i] = nums[j ++]; } return i + 1; } }
161 / 161 test cases passed. Status: Accepted Runtime: 368 ms
相关文章推荐
- Unity3D新手教学,让你十二小时,从入门到掌握!(三 )
- ABCD四个人说真话的概率都是1/3。假如A声称B否认C说D是说谎了,那么D说过的那句话真话的概率是多少
- 第四周工作周报
- String与new String的区别
- SQL实现类似于自动刷新数据的功能
- ABCD四个人说真话的概率都是1/3。假如A声称B否认C说D是说谎了,那么D说过的那句话真话的概率是多少
- Moo University - Financial Aid
- 安卓图片选择版本问题(华为手机会导致oom)
- LeetCode(224) Basic Calculator
- 高效的算法找出中间所有A[i] = i的下标
- iOS加载程序视图的方式
- Java流式IO
- JavaScript随机数
- Moo University - Financial Aid
- 贪心算法的C语言实现与运用详解
- 黑马程序员 集合框架
- vmware后台运行
- JVM参数详解
- Java基础—super和this关键字
- Spring事务传播特性实例解析