【LeetCode-面试算法经典-Java实现】【026-Remove Duplicates from Sorted Array(删除排序数组中的重复元素)】
2015-07-24 07:01
951 查看
【026-Remove Duplicates from Sorted Array(删除排序数组中的重复元素)】
【LeetCode-面试算法经典-Java实现】【所有题目目录索引】
原题
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
1and
2respectively. It doesn’t matter what you leave beyond the new length.
题目大意
给定一个排序的数组,将数组中的重复元素去掉,相同的只保留一个,并且返回数组新的元素个数,不要创建一个新的数组来保存结果。在常量时间内解决这个问题解题思路
从第二个元素开始处理,记为当前处理的元素,如果当前元素与他的前一个元素相同就删除这个元素,如果不同就将它移动到正确的位置,返回最后数组元素人个数。代码实现
算法实现类public class Solution { public int removeDuplicates(int[] A) { if (A.length == 0) { return 0; } int index = 0;//[0,index]只记录数组中出现的按从小到大的唯一一个数,已经排好序了 int next = 1; // 算法思想:找index之后的比A[index]大的数,如是找到就移动到A[index+1]处, // index移动到下一个位置,next移动到下一个位置,再找比A[index]大的数 while (next < A.length) { while (next < A.length && A[index] == A[next] ) { // 找不等于数组中最 next++; } if (next < A.length) { index++; A[index] = A[next]; next++; } } return index + 1; } private void swap(int[] a, int x, int y) { int tmp = a[x]; a[x] = a[y]; a[y] = tmp; } }
评测结果
点击图片,鼠标不释放,拖动一段位置,释放后在新的窗口中查看完整图片。特别说明
欢迎转载,转载请注明出处【/article/1343436.html】
相关文章推荐
- 黑马程序员——Java基础——Map集合的学习
- 黑马程序员--基础整理02
- 黑马程序员——学习一维数组的地址
- 黑马程序员——String类和基本数据类型对象包装类
- 【黑马程序员】-----java基础----IO
- 身为java程序员你需要知道的网站(包含书籍,面试题,架构...)
- 黑马程序员_OC Foundation框架简介
- 黑马程序员——JAVA基础------集合框架(四)----Map集合
- 如何面试一个Android开发者
- 码农《二》
- Android面试
- 码农《一》
- 剑指offer-面试题17.合并两个排序的链表
- iOS程序员面试
- 关于PHP程序员解决问题的能力
- 黑马程序员--基础整理01
- 黑马程序员——JAVA基础------集合框架(三)----Iterator
- 【转】常见数字IC设计、FPGA工程师面试题
- 黑马程序员——Java多线程之线程安全问题
- 剑指offer-面试题16.反转链表