LeetCode:Remove Element

简介:

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

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


题目的意思是把数组中和给定的目标数字不同的元素,全部放到数组的前部

遍历数组,如果在当前位置 i 碰到元素等于给定的目标数字,从数组尾部找一个不等于目标的数字,放到 i 位置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class  Solution {
public :
     int  removeElement( int  A[], int  n, int  elem) {
         int  k = n-1;
         for ( int  i = 0; i <= k; i++)
             if (A[i] == elem)
             {
                 while (k > i && A[k] == elem)k--; //从后面找到第一个不是elem的元素
                 if (k == i) return  i;
                 else  A[i] = A[k--]; //k位置非elem的元素放到i位置
             }
         return  k+1;
     }
};

 

其实遍历找到等于目标数字的元素后,只需要把数组尾部元素放到当前位置,不管尾部元素是否为目标数字            本文地址

1
2
3
4
5
6
7
8
9
10
11
class  Solution {
public :
     int  removeElement( int  A[], int  n, int  elem) {
         int  k = n-1;
         for ( int  i = 0; i <= k;)
             if (A[i] == elem)
                 A[i] = A[k--]; //尾部元素放在当前位置
             else  i++;
         return  k+1;
     }
};

 

还有一种思路是把不等于目标数字的元素依次放到首部,如果不等于目标数字的元素较少,这种方法效率更高

1
2
3
4
5
6
7
8
9
class  Solution {
public :
     int  removeElement( int  A[], int  n, int  elem) {
         int  k = 0;
         for ( int  i = 0; i < n; i++)
             if (A[i] != elem)A[k++] = A[i];
         return  k;
     }
};

 






本文转自tenos博客园博客,原文链接:http://www.cnblogs.com/TenosDoIt/p/3793601.html,如需转载请自行联系原作者

目录
相关文章
|
6月前
Leetcode 230. Kth Smallest Element in a BST
先来看下二叉搜索树的性质,对于任意一个非叶子节点,它的左子树中所有的值必定小于这个节点的val,右子树中所有的值必定大于或等于当前节点的val。 这条性质就保证了如果我们对二叉搜索树做中序遍历,中序遍历的结果肯定是有序的。对于此题而言,我们只需要拿到中序遍历结果,然后返回第k个即可,时间复杂度是O(n)。
46 1
LeetCode 19. 删除链表的倒数第N个节点 Remove Nth Node From End of List
LeetCode 19. 删除链表的倒数第N个节点 Remove Nth Node From End of List
|
算法 Python
LeetCode 169. 多数元素 Majority Element
LeetCode 169. 多数元素 Majority Element
LeetCode 402. Remove K Digits
给定一个以字符串表示的非负整数 num,移除这个数中的 k 位数字,使得剩下的数字最小。
55 0
LeetCode 402. Remove K Digits
|
Python
LeetCode 378. Kth S Element in a Sorted Matrix
给定一个 n x n 矩阵,其中每行和每列元素均按升序排序,找到矩阵中第k小的元素。 请注意,它是排序后的第k小元素,而不是第k个元素。
79 0
LeetCode 378. Kth S Element in a Sorted Matrix
|
算法
LeetCode 229. Majority Element II
给定一个大小为 n 的数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。 说明: 要求算法的时间复杂度为 O(n),空间复杂度为 O(1)。
61 0
LeetCode 229. Majority Element II
LeetCode 203. Remove Linked List Elements
删除链表中等于给定值 val 的所有节点。
59 0
LeetCode 203. Remove Linked List Elements
|
索引
LeetCode 162. Find Peak Element
给定一个输入数组 nums,其中 nums[i] ≠ nums[i+1],找到峰值元素并返回其索引。 数组可能包含多个峰值,在这种情况下,返回任何一个峰值所在位置即可。
75 0
LeetCode 162. Find Peak Element
LeetCode 80 Remove Duplicates from Sorted Array II
给定排序的数组nums,就地删除重复项,使重复项最多出现两次并返回新的长度. 不要为另一个数组分配额外的空间,必须通过使用O(1)复杂度的额外空间来修改输入数组,从而实现此目的.
50 0
LeetCode 80 Remove Duplicates from Sorted Array II
|
Java C++
LeetCode之Remove Element
LeetCode之Remove Element
87 0