Remove Duplicates from Sorted Array
来源:互联网 发布:c语言简单游戏程序代码 编辑:程序博客网 时间:2024/06/15 00:58
原题:
Given a sorted array, remove the duplicates in place such that each element appear onlyonce 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 ofnums being 1
and 2
respectively. It doesn't matter what you leave beyond the new length.
即把排好序的数组重复部分删掉,返回没有重复单元的数组长度。
思考过程:
一开始没有比较好的时间复杂度比较小的思路,看来别人的,豁然开朗。
解题思路:
相当于把原数组所有元素拿起来依次放回去。如果发现数组里已经有了当前要放进去的元素,就不放,找下一个。一共两个指针,一个标记手里的元素,一个标记数组里的元素。
结果代码:
public int removeDuplicates(int[] nums) { int i = 0; for (int j = 0;j < nums.length;j++)//i和j分别用于标记被赋值的位置和遍历到的位置。 if (nums[j] != nums[i]) nums[++i] = nums[j]; return i + 1;}
阅读全文
0 0
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates From Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- 数组指针和指针数组的区别
- 【ccf-201409-1】相邻数对
- 初学javaweb,我选择存储过程——MySql存储过程详解
- 【小白学CV】传统特征点检测算法SIFT详细分析
- table 删除内容
- Remove Duplicates from Sorted Array
- Struts2中s标签的用法
- 动态区间第K大(树状数组+主席树)
- [java源码] Java Web 文章管理系统(Jsp+Ajax+JDBC+MySql实现)
- hibernate延迟加载和session关闭问题
- vue和element框架搭配实现导航条跳转,点击按钮跳转页面导航条也跟着变换
- eval('('+***+')')对json数据格式的作用
- Windows7 64 位系统安装Oracle VM VirtualBox 后没有Ubuntu/Linux 64-bit选项
- Php中的静态变量和静态方法