
----------经典算法题
mfcheer
他不停地跑啊跑 就为了追上那个曾经被寄予厚望的自己
-
原创 LeetCode 2. Add Two Numbers
题目:https://leetcode.com/problems/add-two-numbers/class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { if (l1 == NULL) return l2; if (l2 == NULL) return2016-03-12 01:24:51345
0
-
原创 矩阵旋转
对于n×n矩阵: 90度旋转: 列号变为行号(n - 行号 + 1)变成列号规律: a[i][j] = b[j][n - i + 1] 180度旋转: (n - 行号 + 1)变为行号(n - 列号 + 1)变为列号规律:a[i][j] = b[n - i + 1][n - j + 1] 270度旋转(相当于逆时针旋转90度): 行号变为2014-11-07 19:46:20520
0
-
原创 等概率洗牌算法
遍历数组,遇到第i个元素时,产生一个i到n-1之间的随机数,然后两个位子的数互换。 void shuff(int *ap, int n) { int i; for (i=0; i<n; i++) { int t = rand()%(n-i)+i; swap(a[i],a[t]); } }2014-10-22 00:13:10657
0
-
原创 利用1~7的随机数,产生一个1~10的随机数
必须是等概率的。 int rand10() { int i = rand7() - 1; int j = rand7() - 1; int num = rand7()*i + j; if ( num >= 40 ) return rand10(); else return num%10 + 1; } 这题一开始我做的时候,我以为直接对这个ra2014-10-21 23:42:18860
0
-
原创 字符串循环左移
题目描述: 给定一个字符串S[0…N-1],要求把S的前k 个字符移动到S的尾部,如把字符串“abcdef” 前面的2个字符‘a’、‘b’移动到字符串的尾部, 得到新字符串“cdefab”:即字符串循环左移k。 多说一句:循环左移k位等价于循环右移n-k位。算法要求: 时间复杂度为 O(n),空间复杂度为 O(1)。问题分析: 暴力移位法 每次循环左移1位,调用k次即可2015-06-18 14:38:47825
0
-
原创 Leetcode 151. Reverse Words in a String
题目:https://leetcode.com/problems/reverse-words-in-a-string/代码:class Solution { public: void reverseWords(string &s) { string ans; ans.clear(); for (int i = 0;i != s.siz2016-04-23 22:49:29245
0
-
原创 循环有序数组查找值
循环数组,即有序的数组进行移位后的数组。 如:4,5,6,7,8,0,1,2,3查找值是否存在时,利用二分的思想。 步骤: while(L<R) 如果 a[mid] == key,return mid。 如果a[mid] > a[L],说明L-mid是有序的,mid+1 - R是循环的 如果key<a[mid] && key >= a[L],则key在L - mid-1之间,2016-04-22 22:20:30401
0
-
原创 二叉树层序前序中序后序遍历,深度
层序利用队列: void PrintFromTopToBottom(BinaryTreeNode *pTreeRoot) { if(!pTreeRoot) return; std::queue queTreeNode; dequeTreeNode.push_back(pTreeRoot); while(!queTreeNode.em2014-10-21 23:30:17404
0