1. 反轉二叉樹
解:運用遞歸;反轉左子樹,反轉右子樹,交換左右子樹
2.反轉單鏈表
解:
- 遞歸解法:
Java
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode p = head.next;
ListNode q = reverseList(p);
head.next = null;
p.next = head;
return q;
}
2. 頭插法
```java```
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode p = head.next;
head.next = null; //注意此句
ListNode q;
while(p!=null){
q = p.next;
p.next = head;
head = p;
p = q;
}
return head;
}
3.通過兩個棧實現一個隊列
解: A棧負責裝入,B棧負責取出。取出操作的時候若B棧沒有元素,將A棧元素全部取出壓棧入B。
4. Tencent2013 筆試題:
題目: 用1、2、2、3、4、5這六個數字,用java寫一個main函數,打印出所有不同的排列,如:512234、412345等,要求:"4"不能在第三位,"3"與"5"不能相連。
解析:該題的直觀思想是將6個數組進行全排列,然后去除不符合條件的結果。關于全排列的實現算法,大家可以參考這個鏈接 全排列(含遞歸和非遞歸的解法),這里我們給出兩種其他思路。
解法一:將6個節點構成3和5不連通的無向圖,分別以每個節點為初始節點進行圖的遍歷。結果去重(可以考慮直接將遍歷結果存入set結構中),然后去“4”在第三位的。
Java
public class Tencent2013 {
private String[] b = new String[]{"1", "2", "2", "3", "4", "5"};
private int n = b.length;
private boolean[] visited = new boolean[n];
private int[][] a = new int[n][n];
private String result = "";
private TreeSet<String> set = new TreeSet<String>();
private void run() { //構建圖
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) {
a[i][j] = 0;
} else {
a[i][j] = 1;
}
}
}
// 3 is the 4th num, 5 is the 6th num. can not be neighbor
a[3][5] = 0;
a[5][3] = 0;
for (int i = 0; i < n; i++) {
depthFirstSearch(i);
}
//
for (String str : set) {
if (str.indexOf("4") != 2) {
System.out.println(str);
}
}
}
//深度優先遍歷 graph
private void depthFirstSearch(int i) {
visited[i] = true;
result += b[i];
if (result.length() == n) {
set.add(result);
}
for (int j = 0; j < n; j++) {
if (a[i][j] == 1 && visited[j] == false) {
depthFirstSearch(j);
}
}
result = result.substring(0, result.length() - 1);
visited[i] = false;
}
public static void main(String[] args) {
new Tencent2013().run();
}
}
**解法二**:(思路廣)
該算法的性能比較差,對于有n個數的話,循環的次數是10的n次方級,n如果比較大的話絕對不能采用該法解題。這里只是給出作為一種新穎的思路。
```Java```
//Java代碼
for (int i = 122345; i <= 543221; i++) {
String sb = String.valueOf(i);
String temp = sb.replaceFirst("1", "a");
temp = temp.replaceFirst("2", "a");
temp = temp.replaceFirst("2", "a");
temp = temp.replaceFirst("3", "a");
temp = temp.replaceFirst("4", "a");
temp = temp.replaceFirst("5", "a");
if (!"aaaaaa".equals(temp)) continue;
//排除4在第三位
if (sb.indexOf("4") == 2) continue;
//3 and 5 be together
if (sb.indexOf("35") > -1 || sb.indexOf("53") > -1) continue;
System.out.println(i);
}
5.旋轉字符串
給定一個字符串,要求把字符串前面的若干個字符移動到字符串的尾部,如把字符串“abcdef”前面的2個字符'a'和'b'移動到字符串的尾部,使得原字符串變成字符串“cdefab”。請寫一個函數完成此功能,要求對長度為n的字符串操作的時間復雜度為 O(n),空間復雜度為 O(1)。
解:三步反轉法:
- 將要旋轉的部分反轉
- 將剩余的部分反轉
- 反轉整個字符串
Java
public String reverse(String s) {
StringBuilder builder = new StringBuilder(s);
builder = builder.reverse();
return builder.toString();
}
public String moveToTail(String s, int n) {
String s1 = this.reverse(s.substring(0, n));
String s2 = this.reverse(s.substring(n));
return this.reverse(s1 + s2);
}