Remove Duplicates from Sorted Array 有序数组删除重复元素 @LeetCode
2013-10-14 23:01
417 查看
题目:
给定一个排序过的数组,要求in place的移除重复元素,返回处理后的数组长度
思路:
前后指针,一遍遍历数组即可
变型题是:移除元素后,使得重复出现的元素最多出现2次
http://blog.csdn.net/fightforyourdream/article/details/12883543
给定一个排序过的数组,要求in place的移除重复元素,返回处理后的数组长度
思路:
前后指针,一遍遍历数组即可
变型题是:移除元素后,使得重复出现的元素最多出现2次
http://blog.csdn.net/fightforyourdream/article/details/12883543
/** * * Remove Duplicates from Sorted Array * * 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 A = [1,1,2], * * Your function should return length = 2, and A is now [1,2]. * */ public class S26 { public static void main(String[] args) { int[] A = {1, 1, 2}; System.out.println(removeDuplicates(A)); } public static int removeDuplicates(int[] A) { int len = A.length; if(len < 2){ return len; } // i遍历数组,j指向待检验是否与i相同的下一个数 int i = 0, j = 1; while(i<len && j<len){ if(A[i] == A[j]){ // 如果出现相同 j++; // 则j继续往前找,直到找到不同于A[i]数 }else{ i++; // i跳动要被覆盖的重复那个数 A[i] = A[j]; // 用非重复的j覆盖重复的i j++; // 更新待检验的j } } // 返回长度是下标加1 return i+1; } }
public class Solution { public int removeDuplicates(int[] A) { int len = A.length; if(len <= 1){ return len; } int p = 0, q = 0; while(q < len){ if(A[p] == A[q]){ q++; }else{ p++; A[p] = A[q]; q++; } } return p+1; } }
相关文章推荐
- CSS3的变形处理-笔记
- JAVA基础:将数据库操作封装
- MySQL常用维护管理工具
- Android编程方式开发UI界面和XML文件与Java代码混合控制UI界面
- 使用C语言编写PHP 5.5.4的扩展函数
- 存储XML格式数据的原理
- 使用dom4j和使用Element.selectSingleNode出错解决
- js计算字符串长度,其中中文是utf8格式的
- 流数据挖掘
- ThinkPHP常量参考
- java数组复制的4种方式
- Java多线程间的同步互斥
- PHP字符串长度计算 - strlen()函数
- com
- C语言中有空字符吗?没有!
- 未来一年的自己的来信
- char与signed char, unsigned char的区别
- 多目标优化
- 购物网站核心代码_文件上传_发送邮件_购物车设计_在线支付
- linux就是这个范儿之融于心而表于行(2)