Leetcode (leetcode) classic topic sharing phase 1 - sequence table (array)


This series of blogs mainly explains some of the more classic and common data structure questions in the written test. Since I have just started learning data structures, the updated content must be relatively simple, and the difficulty will increase with the deepening of learning.

27. Remove elements

OJ link
Topic introduction:
Given an array nums and a value val, you need to remove all elements whose value is equal to val in place, and return the new length of the removed array.
Don't use extra array space, you have to use only O(1) extra space and modify the input array in-place.
The order of elements can be changed. You don't need to consider elements in the array beyond the new length.
Source: LeetCode
Link: https://leetcode.cn/problems/remove-element
For specific information, you can open the link to view.

We provide three methods for this question:

Method 1. Violent solution

The general idea is: traverse the array, find the element that needs to be removed, and then remove it.
Time complexity: O(n^2)
Space complexity: O(1)
Graphical ideas:
insert image description here
insert image description here
insert image description here

After finishing, you need to pay attention to two points:

  1. i needs to continue to stay at the current position, and the for loop will cause i++, so we need to do it manuallyi--
  2. After deleting an element in the array, the size of the array becomes smaller and needs to benumsSize--

code show as below:

int removeElement(int* nums, int numsSize, int val)
{
    
    
//遍历数组
    for(int i=0;i<numsSize;i++)
    {
    
    
        if(nums[i]==val)
        {
    
    
            //如果找到了val,从i开始,将数组左移一格
            for(int j=i;j<numsSize-1;j++)
            {
    
    
                nums[j]=nums[j+1];
            }
            //移动完毕后,i--保证下一次还是从i开始遍历,numsSize--表示数组总元素减1
            i--;
            numsSize--;
        }
    }
    return numsSize;
}

Code submission result:

insert image description here

Method 1 Summary

The idea of ​​method 1 is very simple, but the time complexity is very high. Although the task can be completed, the algorithm is not good.

Method 2. Exchange space for time

The general idea is: recreate a new array, and put the values ​​that are not val in the original array into the new array. Then copy the contents of the new array back to the original array.
Time complexity O(n)
space complexity O(n)
graphic ideas:

Please add a picture description
insert image description here
code show as below:

int removeElement(int* nums, int numsSize, int val)
{
    
    
    //动态开辟内存,即开辟一个容量为numSize的新数组
    int* tmp=(int*)malloc(sizeof(int)*numsSize);
    int src=0,dst=0;
    while(src<numsSize)
    {
    
    
        //将原数组中不为val的元素拷贝至新数组中
        if(nums[src]!=val)
        {
    
    
            tmp[dst]=nums[src];
            src++;
            dst++;
        }
        else
        {
    
    
            src++;
        }
    }
    memcpy(nums,tmp,sizeof(int)*dst);
    free(tmp);
    //这里新数组的大小其实就是dst可以画图理解一下
    return dst;
}

operation result:

Method 2 Summary

The idea of ​​exchanging space for time is often encountered in data structures, and I hope everyone can be familiar with it.

Method 3. Optimization of Method 2

Method 2 is already a good algorithm, but can we optimize it? That is to say, can we try to create a new array and operate directly in the original array.
Time complexity O(n)
Space complexity O(1)
Diagram:
Please add a picture description
After completion, the array structure is as follows:
insert image description here
the number of effective elements is j+1
The code is as follows:
insert image description here

int removeElement(int* nums, int numsSize, int val)
{
    
    
	int src = 0, dst = 0;
	int count = 0;
	while (src <= numsSize - 1)
	{
    
    
	    //src不等于val就拷贝并记录拷贝的数据个数
		if (nums[src] == val)
		{
    
    
			src++;
			count++;
		}
		else
		{
    
    
			nums[dst] = nums[src];
			src++;
			dst++;
		}
	}
	return numsSize - count;//这里写成dst+1也可以
}

operation result:
insert image description here

26. Remove duplicates in sorted array

This question is actually similar to the previous one. Provide a better solution, the idea is similar to the method 3 of the previous question.
Idea: The double pointers src and dst point to the first element at the same time at the beginning, if the elements are the same, then src++, otherwise dst++ and copy the content pointed to by src to dst, src++, the number of valid elements in the final array is dst+1.
Graphic:
insert image description here
The code is as follows:

int removeDuplicates(int* nums, int numsSize)
{
    
    
    int src=0,dst=0;
    while(src<numsSize)
    {
    
    
        //相同则跳过,否则就拷贝
        if(nums[src]==nums[dst])
        {
    
    
            src++;
        }
        else
        {
    
    
            dst++;
            nums[dst]=nums[src];
            src++;
        }
    }
    return dst+1;
}

operation result:
insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/m0_72482689/article/details/127649917