标签:free div 三目运算 从尾到头打印链表 amp https new href pre
做有挑战的事情,就从这里开始。
忘记这本书现在在哪儿了,以前还以为能祖祖辈辈留传,现在只能借助 Nowcoder 了。Now coder,Forever thinker。
想以自以为最优美的 code 来体现算法与数据结构的美。
题目:二维数组中的查找
题解:拿左下角 $(rowCount - 1, 0)$ 为起点,如果 $target >a[i][j]$,那么第 $0$ 列就无效了,小于的话,最后一行就无效了,就这样每次删除一行或者一列。
时间复杂度:$O(n + m)$
注意:这题最暴力的做法是 $O(n*m)$ 遍历整个二维数组;稍微优雅的是枚举行,二分列,这样是 $O(n * logm)$
代码:
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
if(array.size() == 0) {
return false;
}
int rowCount = array.size();
int colCount = array[0].size();
int i = rowCount - 1;
int j = 0;
while(i >= 0 && j < colCount) {
if(array[i][j] == target) {
return true;
}
array[i][j] > target ? i -- : j ++;
}
return false;
}
};
题目:替换空格
题解:这题目正着来的话必然需要开辟新的字符数组去存储结果,可以倒着考虑,计算好新数组的长度,倒着更新就可以了。
时间复杂度:$O(length + spaceCount * 2)$
注意:不喜欢 if else 了,三目运算符瞎用
代码:
class Solution {
public:
void replaceSpace(char *str,int length) {
int spaceCount = 0;
for(int i = 0; i < length; i ++) {
str[i] == ‘ ‘ ? spaceCount ++ : 0;
}
int newLength = length + spaceCount * 2;
str[newLength] = 0;
length --;
newLength --;
while(length >= 0) {
str[length] == ‘ ‘ ?
(str[newLength --] = ‘0‘, str[newLength --] = ‘2‘, str[newLength --] = ‘%‘) :
(str[newLength --] = str[length]);
length --;
}
}
};
题目:从尾到头打印链表
题解:正着遍历链表,把结果存到 vector 里面,然后把 vector 倒一下,写这些算法题的时候还是喜欢练童子功,尽量避免调用 STL 函数之类的,手写比较能锻炼 coding 能力和 Bug free。
时间复杂度:$O(listLength)$
代码:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> result;
while(head != NULL) {
result.push_back(head->val);
head = head->next;
}
for(int i = 0; i < result.size() / 2; i ++) {
int t = result[i];
result[i] = result[result.size() - 1 - i];
result[result.size() - 1 - i] = t;
}
return result;
}
};
标签:free div 三目运算 从尾到头打印链表 amp https new href pre
原文地址:https://www.cnblogs.com/zufezzt/p/11215541.html