zoukankan      html  css  js  c++  java
  • Leetcode 题目整理-7 Remove Element & Implement strStr()

    27. Remove Element

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

    Do not allocate extra space for another array, you must do this in place with constant memory.

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

    Example:
    Given input array nums = [3,2,2,3], val = 3

    Your function should return length = 2, with the first two elements of nums being 2.

    Hint:

    1. Try two pointers.
    2. Did you use the property of "the order of elements can be changed"?
    3. What happens when the elements to remove are rare?

    注:对一个无序数组,删除其中数值为val 的元素.提示中提到可以改变顺序,不知是何用意,难不成要先排序,再删除?

    vector<int>::iterator nums_i = nums.begin();
        while( nums_i != nums.end() )
        {
            if (*nums_i == val)
            {
                nums_i = nums.erase(nums_i);
            }
            else{
                nums_i++;
            }    
        }
        return nums.size();

    28. Implement strStr()

    Implement strStr().

    Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

    注:在学习string 的时候看到过现成的函数,但想来这并不是这道题的本意吧。

    int Solution::strStr(string haystack, string needle) {
    
        return haystack.find(needle);
    }
  • 相关阅读:
    04_Windows平台Spark开发环境构建
    Hadoop Streaming 使用及参数设置
    Kafka 及 PyKafka 的使用
    Database Subquery
    Miscellaneous
    Emacs
    算法归纳
    逆元求组合数
    Elasticsearch 原理
    Linux的内存分页管理【转】
  • 原文地址:https://www.cnblogs.com/simayuhe/p/6185920.html
Copyright © 2011-2022 走看看