劍指offer 1

1 二維數組中的查找

public class Solution {
    public boolean Find(int target, int [][] array) {
        if (array.length == 0) {
            return false;
        }
        int len1 = array.length;//求行
        int len2 = array[0].length;//求列
        for (int j = len2 - 1; j >= 0; j--) {
            for (int i = 0; i <= len1 - 1; i++) {
                if (target < array[i][j]) {
                    break;
                }else if (target > array[i][j]) {
                    continue;
                }else {
                    return true;
                }
            }
        }
        return false;
    }
}

2 替換字符串

public class Solution {
    public String replaceSpace(StringBuffer str) {
        if (str == null) {
            return null;
        }
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c == ' ') {
                str.replace(i,i+1,"%20");
            }
        }
        return str.toString();
    }
}

3 從尾到頭打印鏈表

import java.util.Stack;//注意添加包
import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        if (listNode == null) {
            ArrayList<Integer> list = new ArrayList<>();
            return list;
        }
        Stack<Integer> stack = new Stack<>();
        while (listNode != null) {
            stack.push(listNode.val);
            listNode = listNode.next;
        }
        ArrayList<Integer> list = new ArrayList<>();
        while (!stack.isEmpty()) {
            list.add(stack.pop());
        }
        return list;
    }
}

4 重建二叉樹

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.*;
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
         if(pre.length == 0||in.length == 0){
            return null;
        }
        TreeNode node = new TreeNode(pre[0]);
        for(int i = 0; i < in.length; i++){
            if(pre[0] == in[i]){
                node.left = reConstructBinaryTree(Arrays.copyOfRange(pre, 1, i+1), Arrays.copyOfRange(in, 0, i));
                node.right = reConstructBinaryTree(Arrays.copyOfRange(pre, i+1, pre.length), Arrays.copyOfRange(in, i+1,in.length));
            }
        }
        return node;
    }
    
}

5 兩個棧實現隊列

import java.util.Stack;

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node) {
        stack1.push(node);
    }
    
    public int pop() {
        if (stack2.isEmpty()) {//只有當stack2為空時才一次性將stack1中的數據全部壓入
            while (!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }
}

6 旋轉數組的最小數字

//二分查找
import java.util.ArrayList;
public class Solution {
    public int minNumberInRotateArray(int [] array) {
        if (array.length == 0) {
            return 0;
        }
        int low = 0;
        int high = array.length - 1;
        while (low < high) {
            int mid = (low + high) / 2;
            if (array[mid] > array[high]) {//注意是拿mid和high比
                low = mid + 1;
            }else if (array[mid] < array[high]) {
                high = mid;
            }else {
                high -= 1;
            }
        }
        return array[low];
    }
}

7 斐波那契數列

//1,1,2,3,5,8,13,21
public class Solution {
    public int Fibonacci(int n) {
        if (n == 0) {
            return 0;
        }
        int a = 1, b = 1, c = 0;
        if (n == 1 || n == 2) {
            return 1;
        }else {
            for (int i = 3; i <= n; i++) {
                c = a + b;
                a = b;
                b = c;
            }
        }
        return c;
    }
}

8 跳臺階

//變版斐波那契數列:1,2,3,5,8,13,21
//當前臺階的跳法總數=當前臺階后退一階的臺階的跳法總數+當前臺階后退二階的臺階的跳法總數
//n級=n-1級的每個方法后面添上1,n-2級的每個方法后面填上2

public class Solution {
    public int JumpFloor(int target) {
        if (target <= 0) {
            return 0;
        }
        if (target == 1) {
            return 1;
        }
        if (target == 2) {
            return 2;
        }
        int a = 1;
        int b = 2;
        int c = 0;
        for (int i = 3; i <= target; i++) {
            c = a + b;
            a = b;
            b = c;
        }
        return c;
    }
}

9 變態跳臺階

//n = 之前所以方法的和再加1,
//1,2,4,8,16,32
public class Solution {
    public int JumpFloorII(int target) {
        if (target <= 0) {
            return 0;
        }
        if (target == 1) {
            return 1;
        }
        if (target == 2) {
            return 2;
        }
        int sum = 3;
        int c = 0;
        for (int i = 3; i <= target; i++) {
            sum = sum + c;
            c = sum + 1;
        }
        return c;
    }
}

10 矩形覆蓋

//變斐波那契:1,2,3,5,8,13,21;同跳臺階
public class Solution {
    public int RectCover(int target) {
        if (target <= 0) {
            return 0;
        }
        if (target == 1) {
            return 1;
        }
        if (target == 2) {
            return 2;
        }
        int a = 1;
        int b = 2;
        int c = 0;
        for (int i = 3; i <= target; i++) {
            c = a + b;
            a = b; 
            b = c;
        }
        return c;
    }
}

11 二進制中1的個數

//一個數減去1再和這個數做位與運算,結果是將這個數  最  右邊的那位1置0.一直操作直到這個數為0,這樣有幾個1就操作幾次
public class Solution {
    public int NumberOf1(int n) {
        int count = 0;
        while (n != 0) {//java中必須為boolean表達式
            count++;
            n = (n - 1) & n;
        }
        return count;
    }
}

12 數值的整數次方

import java.util.*;
public class Solution {
    public double Power(double base, int exponent) {
        if (base ==0.0 & exponent < 0) {//如果底數為0,且指數為負數,需要取倒數,但0不能做分母。
            return 0.0;
        }
        int abs = Math.abs(exponent);//取絕對值
        double result = pow(base, abs);//求指數為絕對值時的結果
        if (exponent < 0) {
            return 1 / result;
        }
        return result;
  }
    public double pow(double base, int abs) {
        if (abs == 0) {//絕對值為0,返回1.0
            return 1.0;
        }
        if (abs == 1) {//絕對值為1,返回底數
            return base;
        }
        double re = pow(base,abs >> 1);
        re *= re;
        if ((abs & 1) == 1) {//奇數要多乘個base,
            return re *= base;
        }
        return re;
    }
}

13 奇數位于偶數前

//快排,不能保證相對位置不變。
//low奇數,low向后走直到遇到偶數。
//high是偶數,high向前走直到遇到奇數。
//如果low在high前,交換。
public class Solution {
    public void reOrderArray(int [] array) {
        if (array.length == 0) {
            return;
        }        
        int low = 0;
        int high = array.length - 1;
        while (low < high) {
            while ((array[low] & 1) == 1) {//位與比求余效率高
                low += 1;
            }
            while ((array[high] & 1) == 0) {
                high -= 1;
            }
            if (low < high) {
                int temp = array[low];
                array[low] = array[high];
                array[high] = temp;
            }
        }
    }
}
//插入排序,保證相對位置不變
//第1個數先不管,i從第2個數開始向后走,先找到第1個奇數
//j=i,找到j前一個偶數,j向前走,一次換
//2,4,6,5,7:i先走到5,j也定位到5,5和6,4,2依次換
public class Solution {
    public void reOrderArray(int [] array) {
        if (array.length == 0) {
            return;
        }
        for (int i = 1; i < array.length; i++) {
            int target = array[i];
            if ((array[i] & 1) == 1) {//如果為奇數
                int j = i;
                while (j >= 1 && (array[j - 1] & 1) == 0 ) {
                    array[j] = array[j - 1];
                    j--;
                }
                array[j] = target;
            }
        }
    }
}

14 輸入一個鏈表,輸出該鏈表中倒數第k個結點。

/*
1.定義兩個游標p1,p2,其中p2先走k步,然后p1和p2一起走,當p2走到空時,p1為倒數第k個結點
2.需要驗證head為空,k<1,k大于鏈表長度三種情況
*/
public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
        if (head == null || k < 1) 
            return null;
        ListNode p1 = head;
        ListNode p2 = head;
        for (int i = 0; i < k; i++) {
            if (p2 == null)//當k大于鏈表長度時會發生
                return null;
            p2 = p2.next;
        }
        while (p2 != null) {
            p1 = p1.next;
            p2 = p2.next;
        }
        return p1;           
    }
}

15 反轉鏈表

public class Solution {
    public ListNode ReverseList(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode newHead = null;
        ListNode pNode = head;
        ListNode pPre = null;
        while (pNode != null) {
            ListNode pNext = pNode.next;//若pNode一開始為空,這句話寫到外面就是錯的
            if (pNext == null) {
                newHead = pNode;
            }
            pNode.next = pPre;
            pPre = pNode;
            pNode = pNext;
        }
        return newHead;
    }
}

16 合并兩個排序鏈表

public class Solution {
    public ListNode Merge(ListNode list1,ListNode list2) {
        if (list1 == null) {
            return list2;
        }
        if (list2 == null) {
            return list1;
        }
        ListNode node = null;
        if (list1.val <= list2.val) {
            node = list1;
            node.next = Merge(list1.next, list2);
        }else {
            node = list2;
            node.next = Merge(list1, list2.next);
        }
        return node;
    }
}

17 樹的子結構

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public boolean HasSubtree(TreeNode root1,TreeNode root2) {
        if (root1 == null || root2 == null) {
            return false;
        }
        boolean flag = false;
        if (root1.val == root2.val) {//如果根值相同才去判斷是否為子結構,以這個根點開始
            flag = IsSubtree(root1, root2);//判斷是否為子結構的方法
        }
        if (!flag) {//以這個點開始的,不是子結構
            flag = HasSubtree(root1.left, root2);//左子樹結點和root2比
            if (!flag) {
                flag = HasSubtree(root1.right, root2);//如果左子樹不是,比較右子樹
            }
        }
        return flag;
    }
    public boolean IsSubtree(TreeNode root1, TreeNode root2) {
        if (root2 == null) {//右樹已比完,左樹還有,情況正確
            return true;
        }
        if (root1 == null && root2 != null) {//左樹已完,右樹還有,錯誤
            return false;
        }
        if (root1.val == root2.val) {
            return IsSubtree(root1.left, root2.left) && IsSubtree(root1.right, root2.right);
        }else {
            return false;
        }
    }
}

18 樹的鏡像

public class Solution {
    public void Mirror(TreeNode root) {
        if (root == null) {
            return;
        }
        if (root.left == null && root.right == null) {//葉結點
            return;
        }
        TreeNode pTemp = root.left;//交換root的左右子樹
        root.left = root.right;
        root.right = pTemp;
        if (root.left != null) {//還有子結點
            Mirror(root.left);
        }
        if (root.right != null) {
            Mirror(root.right);
        }
    }
}

19 順時針打印矩陣

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printMatrix(int [][] matrix) {
       ArrayList<Integer> list = new ArrayList<>();
       if (matrix.length == 0) return list;
       int len1 = matrix.length;
       int len2 = matrix[0].length;
       int layers = (Math.min(len1, len2) + 1) / 2;
        
       for (int i = 0; i < layers; i++) {
           for (int m = i; m < len2 - i; m++) {//注意考慮一列
               list.add(matrix[i][m]);
           }
           for (int n = i + 1; n < len1 - i; n++) {//注意考慮一行
               list.add(matrix[n][len2 - 1 - i]);
           }
           for (int p = len2 - 2 - i; (p >= i) && (len1 - 1 - i != i);p--) {//防止只有一行
               list.add(matrix[len1 - 1 - i][p]);
           }
           for (int k = len1 - 2 - i; (k > i) && (len2 - 1 - i != i);k--) {//防止只有一列
               list.add(matrix[k][i]);
           }
       }
       return list;
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,002評論 6 542
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,400評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,136評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,714評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,452評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,818評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,812評論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,997評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,552評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,292評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,510評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,035評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,721評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,121評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,429評論 1 294
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,235評論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,480評論 2 379

推薦閱讀更多精彩內容

  • 說明: 本文中出現的所有算法題皆來自牛客網-劍指Offer在線編程題,在此只是作為轉載和記錄,用于本人學習使用,不...
    秋意思寒閱讀 1,165評論 1 1
  • 劍指offer 最近在牛客網上刷劍指offer的題目,現將題目和答案(均測試通過)總結如下: 二維數組的查找 替換...
    閆阿佳閱讀 934評論 0 10
  • 刷題啦刷題啦,劍指offer好像比較有名,所以就在牛客網上刷這個吧~btw,刷了一些題發現編程之美的題好典型啊!!...
    Cracks_Yi閱讀 431評論 0 1
  • 劍指 offer 在一個二維數組中,每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請完成...
    faremax閱讀 2,227評論 0 7
  • 1 二維數組中的查找 2 替換字符串 3 從尾到頭打印鏈表 4 重建二叉樹 5 兩個棧實現隊列 6 旋轉數組的...
    Attitudeljh閱讀 249評論 0 0