记录一些思路一样,可是性能和简洁性被吊打的我的代码,希望可以慢慢从中学到一些写代码的思考方法和思想
leetcode 55.跳跃游戏
我
class Solution {
public:
bool canJump(vector<int>& nums) {
int max = 0, sign = 0;
int flag = 1;
while(flag != max)
{
flag = max;
max = max>(nums[flag]) ? max : (nums[flag]);
for(int i=1; i<=nums[sign] && (i+sign) < nums.size(); i++)
if(max < (sign+i+nums[i+sign]))
{
max = sign+i+nums[i+sign];
sign = i+sign;
}
if(max >= nums.size() - 1)
return true;
}
return false;
}
};
大佬
bool canJump(vector<int>& nums)
{
int k = 0;
for (int i = 0; i < nums.size(); i++)
{
if (i > k) return false;
k = max(k, i + nums[i]);
}
return true;
}
思路相同,我却浪费了那么多空间和运算…
leetcode 136. 只出现一次的数字
题目
我
利用set不会重复存储元素的特点
class Solution {
public:
int singleNumber(vector<int>& nums) {
set<int> ms;
for(auto c:nums)
{
if(ms.count(c) == 0)
ms.insert(c);
else
ms.erase(c);
}
auto c = *ms.begin();
return c;
}
};
大佬
利用了异或位运算的魔力
class Solution {
public:
int singleNumber(vector<int>& nums) {
int ret = 0;
for (auto e: nums) ret ^= e;
return ret;
}
};
我是fw
leetcode 141. 环形链表
题目
我
class Solution {
public:
bool hasCycle(ListNode *head) {
set<ListNode*> ms;
while(head != nullptr)
{
ms.insert(head);
head = head->next;
if(ms.find(head) != ms.end())
return true;
}
return false;
}
};
大佬
利用了快慢指针
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode* slow = head;
while(head != nullptr)
{
if(head->next !=nullptr)
head = head->next->next;
else
head = nullptr;
slow = slow->next;
if(slow == head && slow != nullptr)
return true;
}
return false;
}
};
leetcode 3. 无重复字符的最长子串
题目
我
class Solution {
public:
int lengthOfLongestSubstring(string s) {
string now;
int max = 0, point = 0, i = 0;
while(i < s.length()){
if(now.find(s[i]) != string::npos){
point = now.find(s[i]);
string temp(now);
now.clear();
for(int j = 0; j < temp.length()-point-1; j++)
now += temp[j+point+1];
}
else{
now += s[i];
i++;
}
max = max > now.length() ? max: now.length();
}
return max;
}
};
大佬
int lengthOfLongestSubstring(string s) {
vector<int> m(128, 0);
int ans = 0;
int i = 0;
for (int j = 0; j < s.size(); j++) {
i = max(i, m[s[j]]);
m[s[j]] = j + 1;
ans = max(ans, j - i + 1);
}
return ans;
}