Leetcode练习题Remove Element

Question:

Given an array nums and a value val, remove all instances of that value in-place and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

Example 1:

Given nums = [3,2,2,3], val = 3,

Your function should return length = 2, with the first two elements of nums being 2.

It doesn't matter what you leave beyond the returned length.

Example 2:

Given nums = [0,1,2,2,3,0,4,2], val = 2,

Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.

Note that the order of those five elements can be arbitrary.

It doesn't matter what values are set beyond the returned length.

Solution:

class Solution {
public int removeElement(int[] nums, int val) { int newIndice = 0; for(int i=0;i<nums.length;i++)
{
if(nums[i]!=val)
{
nums[newIndice++] = nums[i];
}
} return newIndice; }
}

在本题中,主要考点是利用两个指针来实现数组内的内容判断和复制。比如,在本题中我利用newIndice来作为一个比原始指针慢的指针来指向过滤后内容的值,并自增,就实现了目标,得到了新的数组。

另外有趣的是,我将本题看成计算数组中有多少个不重复数组的值;另外延伸一下,再计算每个不重复值的个数;

接下来我们一次考虑:

  • 计算数组中有多少个不重复的值:

思路是使用Hashset来计算,因为HashSet中,每个值仅允许出现一次,所以当我们将值都add进去的时候。

import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator; public class hashSet {
public static void main(String[] args)
{
int[] arrays = {1,4,5,2,6,1,10,3};
hashset(arrays);
} public static void hashset(int[] arrays)
{
HashSet hashset = new HashSet();
for(Integer a: arrays)
{
hashset.add(a);
} Iterator iterator = hashset.iterator(); while (iterator.hasNext())
{
System.out.println(iterator.next());
} }
}

最新文章

  1. Unity3D之GUITexture的坐标体系
  2. MySql的一些操作
  3. [CareerCup] 17.14 Unconcatenate Words 断词
  4. MySQL functions, IF, CASE
  5. [Spring MVC] - @ModelAttribute使用
  6. mysqld_multi部署mysql单机多实例
  7. Saving HDU
  8. 在SQL Server 实现递归
  9. maven jetty plugin
  10. c# 应用NPOI 获取Excel中的图片,保存至本地的算法
  11. pat 喊山
  12. Ubuntu的软件管理与安装
  13. JS实现奇偶数的判断
  14. DOM的基本操作
  15. 解决UnicodeEncodeError。python的docker镜像增加locale 中文支持
  16. python selenium-webdriver 生成测试报告 (十四)
  17. Docker Basic
  18. Bootstrap表单构造器
  19. UVA-10655 Contemplation! Algebra (矩阵)
  20. Flutter 案例学习之:GridView

热门文章

  1. Linux网络基础协议和ip管理
  2. [转]使用IConfigureNamedOptions和ConfigureAll配置命名选项
  3. rxJava2.x源码解析
  4. Python - 部分PEP8规范
  5. Spring Cloud Gateway-自定义异常处理
  6. 怎样深入学习php,成为php高手!?
  7. chrome调试安卓机出现“HTTP/1.1 404 Not Found ”错误
  8. Python “ValueError: incomplete format” upon print(“stuff %” % “thingy”) 解决方法
  9. Linux下环境变量(.bash_profile和.bashrc的区别)
  10. 【cf375】D. Tree and Queries(dsu on tree+线段树)