File tree 3 files changed +76
-0
lines changed
3 files changed +76
-0
lines changed Original file line number Diff line number Diff line change
1
+ /* *
2
+ * Definition for singly-linked list.
3
+ * struct ListNode {
4
+ * int val;
5
+ * ListNode *next;
6
+ * ListNode(int x) : val(x), next(NULL) {}
7
+ * };
8
+ */
9
+ class Solution {
10
+ public:
11
+ ListNode* mergeTwoLists (ListNode* l1, ListNode* l2) { // 代码复用
12
+ if (l1 == NULL ) return l2;
13
+ if (l2 == NULL ) return l1;
14
+ if (l2->val < l1->val ) swap (l1, l2);
15
+ ListNode* curl1 = l1;
16
+ ListNode* lastl1 = l1;
17
+ while (l2 != NULL ) { // merge l2 into l1
18
+ if (curl1 == NULL ) {
19
+ lastl1->next = l2;
20
+ break ;
21
+ } else {
22
+ if (curl1->val <= l2->val ) {
23
+ lastl1 = curl1;
24
+ curl1 = curl1->next ;
25
+ } else {
26
+ lastl1->next = l2;
27
+ lastl1 = l2;
28
+ ListNode* tmp = l2->next ;
29
+ l2->next = curl1;
30
+ l2 = tmp;
31
+ }
32
+ }
33
+ }
34
+ return l1;
35
+ }
36
+ ListNode* mergeKLists (vector<ListNode*>& lists) { // 分治
37
+ int n = lists.size ();
38
+ int interval = 1 ;
39
+ while (interval < n) {
40
+ for (int i=0 ; i<n-interval; i+=2 *interval) {
41
+ lists[i] = mergeTwoLists (lists[i], lists[i + interval]);
42
+ }
43
+ interval *= 2 ;
44
+ }
45
+ if (n) return lists[0 ];
46
+ else return NULL ;
47
+ }
48
+ };
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ bool isUgly (int num) {
4
+ if (num <= 0 ) return false ;
5
+ while (num && num % 2 == 0 ) num /= 2 ;
6
+ while (num && num % 3 == 0 ) num /= 3 ;
7
+ while (num && num % 5 == 0 ) num /= 5 ;
8
+ return (num == 1 );
9
+ }
10
+ };
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ int strStr (string haystack, string needle) {
4
+ if (needle == " " ) return 0 ;
5
+ int m = haystack.length (), n = needle.length ();
6
+ int curPos = 0 ;
7
+ for (int i=0 ; i<m; i++) {
8
+ if (haystack[i] == needle[curPos]) {
9
+ curPos++;
10
+ if (curPos == n) return i - curPos + 1 ;
11
+ } else {
12
+ i = i - curPos;
13
+ curPos = 0 ;
14
+ }
15
+ }
16
+ return -1 ;
17
+ }
18
+ };
You can’t perform that action at this time.
0 commit comments