LeetCode刷题——简单26 Remove Duplicates from Sorted Array

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a247027417/article/details/82585378

问题描述

Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory.

Example 1:

Given 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 returned length.

Example 2:

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

Your function should return length =5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively

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

代码前思考

从描述中可以知道,返回值为int型Length,并且需要修改nums数组。使用index作为数组的下标指示,遍历数组,使用Length_tmp作为已知非重复数据长度。移动index,每次移动,将nums[index]与nums[0-Length_tmp]进行对比,出现相同值则不进行操作index++,未出现不同的值则将nums[index]与nums[Length_tmp]交换。第一版代码如下::

第一版代码

  public int removeDuplicates(int[] nums) {
    	if(nums.length==1)
    		return 1;
		int index = 1;
		int Length_tmp = 1;
		for(;index<nums.length;index++)
		{
			int flag = 0;
			for(int j=0; j<Length_tmp;j++)
			{
				if(nums[index] == nums[j])
					{
						flag = 1;
						break;
					}
			}
			if(flag==0)
			{
				int tmp;
				tmp = nums[Length_tmp];
				nums[Length_tmp] = nums[index];
				nums[index] = tmp;
				Length_tmp++;
			}
			
		}
    	
    	return Length_tmp;
    }

提交LeetCode查看结果

Accepted,结果通过,但是效率极低。考虑优化代码。下面分析高效率代码。题中不需要保持数组的元数据都在,只需要前几个是不重复即可,所以不需要更换两者的位置,只需要将nums[index]赋值给nums[Length_tmp].再看效率。

    public int removeDuplicates(int[] nums) {  
    	
  	if(nums.length==0)
  		return 0;
		int index = 1;
		int Length_tmp = 1;
		for(;index<nums.length;index++)
		{
			if(nums[index-1]<nums[index])
				{
					nums[Length_tmp] = nums[index];
					Length_tmp++;
				}
		}
  	
  	return Length_tmp;
  }

效率略有提高,但没有实现超高效率,需要进一步研究。

猜你喜欢

转载自blog.csdn.net/a247027417/article/details/82585378