• [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.

     解题思路:

    从前往后扫一遍,遇到elem,试图从后往前找一个元素与之交换,如果找不到可以交换的元素,则停止。注意elem如果没有出现,则应该返回n。

    class Solution {
    public:
        int removeElement(int A[], int n, int elem) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            int tmp = 0, len = 0, left = 0, right = n - 1;//0 for 
            for(left = 0;left < n;left++)
            {
                if(A[left] == elem)
                {
                    bool flag = false;
                    for(int i = right; i > left; i--)
                    {
                        if(A[i] != elem)
                        {
                            tmp = A[i];
                            A[i] = A[left];
                            A[left] = tmp;
                            right = i - 1;
                            flag = true;
                            break;
                        }
                    }
                    if(flag == false)
                        return left;
                }
                else
                {
                    if(left == right)
                        return left + 1;
                }
            }
            
            return n;
        }
    };
  • 相关阅读:
    常见mysql中出现的问题
    php 根据身份证号相关操作
    Linux的上传文件和下载文件
    php实现socket
    PHP开启缓存加速
    spark使用Hive表操作
    部署ganglia3.7
    Redis Cluster架构优化
    spark读取hdfs数据本地性异常
    spark join broadcast优化
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3416466.html
Copyright © 2020-2023  润新知