zoukankan      html  css  js  c++  java
  • [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;
        }
    };
  • 相关阅读:
    mod_rewrite
    敏捷开发
    转python和ruby的相同点
    ESB总线知识小结
    使用 squid 2.7 for windows 进行无缓存反向代理
    初探K2workflow
    没激情的工作
    多易拍 二次开发
    查看数二进制代码片段
    生成随机数
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3416466.html
Copyright © 2011-2022 走看看