Skip to content

Commit d89f616

Browse files
ChunelFengjunfeng.fjyanglbme
authored
更新了[lcof-03.数组中重复的数字]和[lcof-06.从尾到头打印链表]的cpp解法 (doocs#342)
* 更新了[lcof-03.数组中重复的数字]和[lcof-06.从尾到头打印链表]的cpp解法 * Update README.md Co-authored-by: junfeng.fj <junfeng.fj@alibaba-inc.com> Co-authored-by: Yang Libin <contact@yanglibin.info>
1 parent a6ff14a commit d89f616

File tree

4 files changed

+103
-0
lines changed

4 files changed

+103
-0
lines changed

lcof/面试题03. 数组中重复的数字/README.md

+24
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,30 @@ func findRepeatNumber(nums []int) int {
120120
}
121121
```
122122

123+
### **C++**
124+
125+
```cpp
126+
class Solution {
127+
public:
128+
int findRepeatNumber(vector<int>& nums) {
129+
int len = nums.size();
130+
for (int i = 0; i < len; i++) {
131+
while (i != nums[i]) {
132+
// 这一位的值,不等于这一位的数字
133+
if (nums[i] == nums[nums[i]]) {
134+
// 如果在交换的过程中,发现了相等的数字,直接返回
135+
return nums[i];
136+
}
137+
138+
swap(nums[i], nums[nums[i]]);
139+
}
140+
}
141+
142+
return 0;
143+
}
144+
};
145+
```
146+
123147
### **...**
124148

125149
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution {
2+
public:
3+
int findRepeatNumber(vector<int>& nums) {
4+
int len = nums.size();
5+
for (int i = 0; i < len; i++) {
6+
while (i != nums[i]) {
7+
// 这一位的值,不等于这一位的数字
8+
if (nums[i] == nums[nums[i]]) {
9+
// 如果在交换的过程中,发现了相等的数字,直接返回
10+
return nums[i];
11+
}
12+
13+
swap(nums[i], nums[nums[i]]);
14+
}
15+
}
16+
17+
return 0;
18+
}
19+
};

lcof/面试题06. 从尾到头打印链表/README.md

+33
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,39 @@ func reversePrint(head *ListNode) []int {
122122
}
123123
```
124124

125+
### **C++**
126+
127+
```cpp
128+
/**
129+
* Definition for singly-linked list.
130+
* struct ListNode {
131+
* int val;
132+
* ListNode *next;
133+
* ListNode(int x) : val(x), next(NULL) {}
134+
* };
135+
*/
136+
class Solution {
137+
public:
138+
vector<int> ret;
139+
140+
void getVal(ListNode* head) {
141+
// 这里可以看成是一个节点的树
142+
if (head) {
143+
if (head->next) {
144+
getVal(head->next);
145+
}
146+
ret.push_back(head->val);
147+
}
148+
}
149+
150+
vector<int> reversePrint(ListNode* head) {
151+
getVal(head);
152+
// 返回的是全局的ret信息。在getVal函数中被赋值
153+
return ret;
154+
}
155+
};
156+
```
157+
125158
### **...**
126159
127160
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
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+
10+
class Solution {
11+
public:
12+
vector<int> ret;
13+
14+
void getVal(ListNode* head) {
15+
if (head) {
16+
if (head->next) {
17+
getVal(head->next);
18+
}
19+
ret.push_back(head->val);
20+
}
21+
}
22+
23+
vector<int> reversePrint(ListNode* head) {
24+
getVal(head);
25+
return ret;
26+
}
27+
};

0 commit comments

Comments
 (0)