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);
}

 

posted @ 2016-12-16 10:30  司马_羽鹤  阅读(125)  评论(0编辑  收藏  举报