LeetCode日記1

第一題html

錯誤思路:數組

(1)不能直接用雙重for循環判斷兩個數相加等於target,會超時。
函數


正確思路:spa

(1)用一個結構體記錄數字和數字的index。指針

(2)用qsort對結構體的vector排序。code

(3)雙重for循環從排序後的vector的兩頭向中間,判斷。orm

(4)找到後判斷兩個結構index的大小,先輸出小的。htm


參考:對象

http://www.acmerblog.com/leetcode-two-sum-5223.html blog


其餘:

(1)快速排序

void qsort(

   void *base,

   size_t num,

   size_t width,

   int (__cdecl *compare )(const void *, const void *) 

);

base

目標數組的開頭。

num

元素的數組大小。

width

以字節爲單位的元素大小。

compare

給比較兩個數組的元素並返回值指定這些關係的一個用戶提供的實例的指針。

(2)vs查看函數原型的方法

光標停留在函數上,按F1鏈接到MSDN。



第二題

(1)用new動態分配對象。

問題:

(1)new的相關知識。



第三題

題目:

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
    	int repeat, prej = 0;
    	unsigned int length = 0;
    	for (string::size_type i = 0; i < s.size(); i++){
    		for (string::size_type j = prej + 1; j < s.size(); j++){
    			repeat = 0;
    			for (string::size_type k = i; k < j; k++){
    				if (s[k] == s[j]){
    					repeat = 1;
    					prej = j;
    					if ((j - i) > length) length = j - i;
    					i = k;
    					break;
    				}
    			}
    			if (repeat == 0) {
    			    if(j == s.size() - 1)
    			        if ((j - i + 1) > length) length = j - i + 1 ;
    			    continue;
    			}
    			else break;
    		}
    	}
    	if(prej == 0) length = s.size();
    	return length;
    }
};

(1)說明  

i指向所判斷子字符串的首元素,j指向所判斷子字符串的尾元素,k用於遍歷子字符串判斷是否出現重複。prej用於記錄上一次出現重複的字符的位子,若出現字符重複時,下次循環分別使ij指向兩個重複字符的下一個位子。

(2)何時計算長度。

1)prej == 0,說明沒有進入判斷兩個字符相同的邏輯;或者字符串的長度爲0,沒有進入第一重for循環;或者字符串的長度爲1,沒有進入第二重for循環。此時length = s.size();

2)當判斷兩個字符相同時。此時長度計算公式是 length = j - i ;

3)當j指向原字符串的尾元素時。此時長度計算公式是 length = j - i + 1 ;

相關文章
相關標籤/搜索