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);
    }
  • 相关阅读:
    结对编程总结
    《构建之法》第4章读后感
    复利计算程序单元测试(C语言)
    命令解释程序的编写实验报告
    《软件工程》前三章读后感
    复利计算的总结
    复利单利计算的功能解释
    构建之法:1、2、3章阅读后感
    复利计算4.0
    复利计算3.0 以及总结
  • 原文地址:https://www.cnblogs.com/simayuhe/p/6185920.html
Copyright © 2011-2022 走看看