欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

【LeetCode从零单排】No26.Remove Duplicates from Sorted Array

发布时间:2025/4/5 编程问答 40 豆豆
生活随笔 收集整理的这篇文章主要介绍了 【LeetCode从零单排】No26.Remove Duplicates from Sorted Array 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

题目

     题目要求:去除sort int数组中的重复项。
     

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 A = [1,1,2],

Your function should return length = 2, and A is now [1,2].


代码

public class Solution {public int removeDuplicates(int[] A) {if (A.length==0) return 0;int length =A.length;int[] B=new int[length];int index=0;//B指向下一个位数int temp=0;//B已经赋值的位置for(int i=0;i<length;i++){//如果第一项是零的情况{0,0,2}if(A[i]==0 && index==0){B[index]=0;index+=1;}if(A[i]!=B[temp]){B[index]=A[i];temp=index;index+=1;} }//给A赋值for(int k=0;k<index;k++){A[k]=B[k];}return index;} }


代码下载:https://github.com/jimenbian/GarvinLeetCode


/********************************

* 本文来自博客  “李博Garvin“

* 转载请标明出处:http://blog.csdn.net/buptgshengod

******************************************/


总结

以上是生活随笔为你收集整理的【LeetCode从零单排】No26.Remove Duplicates from Sorted Array的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。