Leetcode每天兩題11-第27題和第28題

27. Remove Element

給定數組和一個數值v,不改變元素順序的情況下移除所有的v

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 by modifying the input array in-place with O(1) extra memory.

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

Example:

Given nums = [3,2,2,3], val = 3,

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

代碼+注釋

class Solution {public: int removeElement(vector<int>& nums, int val) { //挨個循環判斷,不等於val的保留 int idx = 0; int n = nums.size(); if (n == 0) return 0; for (int i = 0; i<n; i++) { if (nums[i] != val) { nums[idx++] = nums[i]; } } return idx; }};

28. Implement strStr()

從母字元串中找到出現子字元串的位置

Implement strStr().

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

Example 1:

Input: haystack = "hello", needle = "ll"

Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"

Output: -1

代碼+注釋

class Solution {public: int strStr(string haystack, string needle) { //母字元串長度小於子字元串長度時返回-1; //自字元串長度等於0時返回0; //剩下的情況,從母字元串的第0個位置起到第hLength-nLength號位置,依次判斷每個字元是否和needle里的每個字元相等 int hLength = haystack.size(); int nLength = needle.size(); if (nLength == 0) return 0; if (nLength > hLength) return -1; else { for (int i = 0; i <= hLength - nLength; i++) { int j = 0; for (j = 0; j < nLength; j++) { if (haystack[i + j] != needle[j]) { break; } } if (j == nLength) return i; } } return -1; }};

推薦閱讀:

C++中如何載入100K+的常數數組?
寫個編譯器,把C++代碼編譯到JVM的位元組碼可不可行?
怎樣解決Qt發布程序體積過大的問題?
關於c++模板推導失敗,這是編譯器的bug嗎?
如何寫優美的c++代碼?

TAG:LeetCode | CC | 演算法與數據結構 |