博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
RemoveDuplicatesFromSortedArrayI II,移除有序数组里的重复元素以及移除数组里的某个元素...
阅读量:4576 次
发布时间:2019-06-08

本文共 1811 字,大约阅读时间需要 6 分钟。

RemoveDuplicatesFromSortedArrayI:

问题描述:给定一个有序数组,去掉其中重复的元素。并返回新数组的长度。不能使用新的空间。

[1,1,2,3] -> [1,2,3] 3

算法思路:用一个数字记录新数组的最后一个元素的位置

1 public class RemoveDuplicatesFromSortedArray { 2      3     public int removeDuplicates(int[] nums) 4     { 5         if(nums.length == 0) 6         { 7             return 0; 8         } 9         int key = nums[0];10         int count = 0;//记录新数组最后一个元素的位置,即新数组长度11         for(int i = 0; i < nums.length; i ++)12         {13             if(nums[i]!=key)14             {15                 nums[count++] = key;16                 key = nums[i];17             }18         }19         nums[count++] = key;20         return count;21     }22 }

 与之类似的就是移除数组里某个元素。

1 public int removeElement(int[] nums, int val) { 2         if(nums.length == 0) 3         { 4             return 0; 5         } 6         int count = 0; 7         for(int i = 0; i < nums.length; i ++) 8         { 9             if(nums[i]!=val)10             {11                 nums[count++] = nums[i];12             }13         }14         return count;15     }

 RemoveDuplicatesFromSortedArrayII:

问题描述:可以重复一次。

For example,

Given sorted array nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of nums being 1122 and 3. It doesn't matter what you leave beyond the new length.

算法分析:这种题目,要巧妙利用数组的下标,和上一题解法相似,只不过,循环里的判断条件变了。

//[1,1,1,2,2,3] -> [1,1,2,2,3] 5 允许重复一次public class RemoveDuplicatesfromSortedArrayII {	public int removeDuplicates(int[] nums) 	{		if(nums.length == 0 || nums.length == 1)		{			return nums.length;		}		int count = 1, temp = nums[1];		for(int i = 2; i < nums.length; i ++)		{			if(nums[i] != nums[i - 2])			{				nums[count++] = temp;				temp = nums[i];			}		}		nums[count++] = temp;		return count;    }}

 

转载于:https://www.cnblogs.com/masterlibin/p/5549545.html

你可能感兴趣的文章
Minimum Depth of Binary Tree,求树的最小深度
查看>>
解决Web部署 svg/woff/woff2字体 404错误
查看>>
fiddler 抓取 nodejs
查看>>
1.Nginx服务应用
查看>>
MySQL基础
查看>>
凹凸贴图与法线贴图
查看>>
sqlserver跨服务器数据库sql语句
查看>>
设计模式-结构型模式,外观模式(6)
查看>>
Trie模版
查看>>
2018HDU多校训练-3-Problem F. Grab The Tree
查看>>
2016012032四则运算网页版结对项目报告
查看>>
淘宝专业版改基础版方法
查看>>
[转]ARM Pipeline
查看>>
[转]Blocking Code Injection on iOS and OS X
查看>>
自动化测试
查看>>
vue $options 获取自定义属性
查看>>
Vue避免 v-if 和 v-for 用在一起
查看>>
TraceSource记录程序日志
查看>>
【Source教程】GCFScape下载安装与使用
查看>>
数据结构 单链表反转 回顾练习
查看>>