[LeetCode]27.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.

【题意】

把数组中与给定值相同的元素删除,在原数组上修改,返回值是最终元素个数。

【分析】

【代码】

/*********************************
*   日期:2014-01-19
*   作者:SJF0115
*   题号: Remove Element
*   来源:http://oj.leetcode.com/problems/remove-element/
*   结果:AC
*   来源:LeetCode
*   总结:
**********************************/
#include <iostream>
#include <stdio.h>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;

class Solution {
public:
    int removeElement(int A[], int n, int elem) {
        int index = 0;
        for(int i = 0;i < n;i++){
            if(A[i] != elem){
                A[index++] = A[i];
            }
        }
        return index;
    }
};
int main() {
    Solution solution;
    int result;
    int A[] = {3,2,5,4,2,6,3,2};
    result = solution.removeElement(A,8,2);
    for(int i = 0;i < result;i++){
        printf("%d ",A[i]);
    }
    printf("\nLength:%d\n",result);
    return 0;
}




【代码2】

class Solution {
public:
    int removeElement(int A[], int n, int elem) {
        return distance(A,remove(A,A+n,elem));
    }
};


目录
相关文章
Leetcode 230. Kth Smallest Element in a BST
先来看下二叉搜索树的性质,对于任意一个非叶子节点,它的左子树中所有的值必定小于这个节点的val,右子树中所有的值必定大于或等于当前节点的val。 这条性质就保证了如果我们对二叉搜索树做中序遍历,中序遍历的结果肯定是有序的。对于此题而言,我们只需要拿到中序遍历结果,然后返回第k个即可,时间复杂度是O(n)。
111 1
|
Python
LeetCode 378. Kth S Element in a Sorted Matrix
给定一个 n x n 矩阵,其中每行和每列元素均按升序排序,找到矩阵中第k小的元素。 请注意,它是排序后的第k小元素,而不是第k个元素。
169 0
LeetCode 378. Kth S Element in a Sorted Matrix
|
算法
LeetCode 229. Majority Element II
给定一个大小为 n 的数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。 说明: 要求算法的时间复杂度为 O(n),空间复杂度为 O(1)。
192 0
LeetCode 229. Majority Element II
|
索引
LeetCode 162. Find Peak Element
给定一个输入数组 nums,其中 nums[i] ≠ nums[i+1],找到峰值元素并返回其索引。 数组可能包含多个峰值,在这种情况下,返回任何一个峰值所在位置即可。
157 0
LeetCode 162. Find Peak Element
|
算法 Python
LeetCode 169. 多数元素 Majority Element
LeetCode 169. 多数元素 Majority Element
LeetCode 215. Kth Largest Element in an Array
在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
200 0
|
Java C++
LeetCode之Remove Element
LeetCode之Remove Element
160 0
|
Unix Shell Linux
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
本文提供了几个Linux shell脚本编程问题的解决方案,包括转置文件内容、统计词频、验证有效电话号码和提取文件的第十行,每个问题都给出了至少一种实现方法。
194 6
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
|
Python
【Leetcode刷题Python】剑指 Offer 32 - III. 从上到下打印二叉树 III
本文介绍了两种Python实现方法,用于按照之字形顺序打印二叉树的层次遍历结果,实现了在奇数层正序、偶数层反序打印节点的功能。
144 6
|
搜索推荐 索引 Python
【Leetcode刷题Python】牛客. 数组中未出现的最小正整数
本文介绍了牛客网题目"数组中未出现的最小正整数"的解法,提供了一种满足O(n)时间复杂度和O(1)空间复杂度要求的原地排序算法,并给出了Python实现代码。
314 2

热门文章

最新文章

下一篇
日志分析软件