leetcode 排序数组去重复并返回新数组长度Remove Duplicates from Sorted Array
2015-08-12 10:50
459 查看
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.
本数组已经排序好数组,不仅仅要返回去重后长度,也要实现去重:
一开始思路:
假定数组nums在0-j之内无重复,则从j+1-numsize-1之中任意一个元素i与(0-j)比较,如都不相同则num[j+1]=num[i]
改变思路,利用已经排好序,相同的则是相连的:
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.
本数组已经排序好数组,不仅仅要返回去重后长度,也要实现去重:
一开始思路:
假定数组nums在0-j之内无重复,则从j+1-numsize-1之中任意一个元素i与(0-j)比较,如都不相同则num[j+1]=num[i]
int removeDuplicates1(int* nums, int numsSize) { int i,j=0,k; int l=numsSize; for(i=1;i<numsSize;i++){ k=0; while(k<=j&&nums[k]!=nums[i])k++; if(k>j)nums[++j]=nums[i]; } numsSize=j+1; return numsSize; }后来发现时间复杂度过大o(n^2)
改变思路,利用已经排好序,相同的则是相连的:
int removeDuplicates(int* nums, int numsSize){ int k=0; int i; for(i=1;i<numsSize;i++) {if(nums[i]!=nums[i-1])nums[i-k]=nums[i]; else k++; } return numsSize-k;}
相关文章推荐
- LeetCode题解:Summary Ranges
- .net4.5注册到iis
- jquery中修改一个元素的值或内容
- Win7(x64)升级到Win10
- 快速理解备份以及服务器使用术语
- new与alloc init,[NSArray array] 和 [[NSArray alloc]init] 及 self. 和 _ 的区别
- 新型程序设计语言:Braise语言!
- SSG140 web、telnet、ssh无法访问,仅支持console
- JUC 原子类
- Ubuntu14.04 源码安装MJPG-Streamer及使用
- Linux 学习笔记------目录处理命令:ls
- xilinx bit流生成错误
- UVA 567 Risk【floyd】
- ios开发之实现长按UITableViewCell弹出UIMenuController
- JavaScript快速掌握
- 微信公众平台开发 上传下载多媒体文件
- 一文让你彻底了解iOS字体相关知识
- KMP 算法
- QGIS python开发手册--使用栅格图层
- Android动画详解