首页 > 作文

java清空数组的方法(java初始化数组赋值)

更新时间:2023-04-04 06:35:38 阅读: 评论:0

26. remove duplicates from sorted array

easy

given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns 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.

clarification:

confud why the returned value is an integer but your answer i剪彩s an array?

乳浊液的定义note that the input array is pasd in by reference, which means a modification to the input array will be known to the caller as well.

internally you can think of t初二数学教材his:

// nums is pasd in by reference. (i.e., without making a copy)int len = removeduplicates(nums);// any modification to nums in your中国文明网向国旗敬礼2020 function would be known by the caller.// using the length returned by your function, it prints the first len elements.for (int i = 0; i < len; i++) {  print(nums[i]);}

example 1:

input: nums = [1,1,2]output: 2, nums = [1,2]explanation: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 returned length.

example 2:

input: nums = [0,0,1,1,1,2,2,3,3,4]output: 5, nums = [0,1,2,3,4]explanation:your function should return length = 5, with the first five elements of nums being modified to0, 1, 2, 3, and4 respectively. it doesn't matter what values are t beyondthe returned length.

constraints:

0 <= nums.length <= 3 * 104-104 <= nums[i] <= 104nums is sorted in ascending order.

给定一个有序数组,删除重复内容,使每个元素只出现一次,并返回新的长度。

题目要求不要为其他数组分配额外的空间,您必须通过在 o(1)额外的内存中就地修改输入数组来实现这一点。

解题思路:

这是一道难度简单的题目,已知条件数组是已排序的,且不能新建数组,这就是告诉我们除了创建数组指针只能改变给定数组来得到结果。

class solution {    public int removeduplicates(int[] nums) {        int n = nums.length;        if (n == 0) {            return 0; //首先排除边界的ca        }              int counter = 0, i = 1; //定义两个指针,counter代表当前去重的长度,i是遍历的指针,为什么i是从1开始? 因为起始位置的数组元素已经计算到结果中,所以开始从二个元素遍历        while(i < n) {            if (nums[counter] == nums[i]) { //判断当前遍历的数组元素和去重后的最大数组元素是否相同,如果相同则继续遍历,不做任何操作。                 i++;            } el { //如果不同,则将数组当前遍历的元素替换到去重数组                counter++; //在替换前首先将去重指针后移一位                nums[counter] = nums[i];                i++; //继续遍历            }        }        return counter + 1; //counter是去重指针的最后一位,所以长度需要加1    }}

总结:这类数组去重的题会经常出现在面试环节中(3sum),看到数组去重我们就要想到对数组先进行排序,然后通过一个n的遍历就能解决问题。

另外就是不占用额外空间,只能新建指针和当前给定的数组来操作。

本文发布于:2023-04-04 06:35:37,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/zuowen/078ffe6ada674d7210874128e7839cf0.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

本文word下载地址:java清空数组的方法(java初始化数组赋值).doc

本文 PDF 下载地址:java清空数组的方法(java初始化数组赋值).pdf

标签:数组   遍历   指针   元素
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图