1. 程式人生 > >【劍指offer】1-10題

【劍指offer】1-10題

1.賦值運算函式

思路:

    將返回值型別宣告為該型別的引用     把傳入的引數型別宣告為常量引用     釋放例項自身已有的記憶體     判斷傳入的引數和當前的例項是不是同一個例項

2.單例設計模式

思路及程式碼實現請參考:單例設計模式程式碼實現

3.在一個二維陣列中,每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請完成一個函式,輸入這樣的一個二維陣列和一個整數,判斷陣列中是否含有該整數。

思路:從右上角或左下角開始找,逐行刪除,或者用二分法查詢

程式碼實現:

public boolean find(int[][] array,int target) {
    if (array == null) {
        return false;
    }
    int row = 0;
    int column = array[0].length-1;

    while (row < array.length && column >= 0) {
        if(array[row][column] == target) {
            return true;
        }
        if(array[row][column] > target) {
            column--;
        } else {
            row++;
        }
    }
    return false;
}

4.將一個字串中的空格替換成“%20”。 例如,當字串為We Are Happy.則經過替換之後的字串為We%20Are%20Happy。

思路:從後往前複製,陣列長度會增加,或使用StringBuilder、StringBuffer類

程式碼實現:

public String replaceSpace(StringBuffer str) {
    if (str == null)
        return null;
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < str.length(); i++) {
        if (String.valueOf(str.charAt(i)).equals(" ")) {
            sb.append("%20");
        }else {
            sb.append(str.charAt(i));
        }
    }
    return String.valueOf(sb);
}

5.輸入一個連結串列,從尾到頭列印連結串列每個節點的值。

思路:藉助棧實現,或使用遞迴的方法。

程式碼實現:

public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
    ArrayList<Integer> list = new ArrayList<>();
    if (listNode == null)
        return list;
    Stack<ListNode> stack = new Stack<>();
    while (listNode != null) {
        stack.push(listNode);
        listNode = listNode.next;
    }

    while (!stack.isEmpty()) {
        list.add(stack.pop().val);
    }
    return list;
}

6.輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。

思路:先找出根節點,然後利用遞迴方法構造二叉樹

程式碼實現:

static class TreeNode {
     int val;
     TreeNode left;
     TreeNode right;
     TreeNode(int x) { val = x; }
 }
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
    if (pre == null || in == null) {
        return null;
    }
    if (pre.length == 0 || in.length == 0) {
        return null;
    }
    if (pre.length != in.length) {
        return null;
    }
    TreeNode root = new TreeNode(pre[0]);
    for (int i = 0; i < pre.length; i++) {
        if (pre[0] == in[i]) {
            root.left = reConstructBinaryTree(
                            Arrays.copyOfRange(pre,1,i+1),Arrays.copyOfRange(in,0,i));
            root.right = reConstructBinaryTree(
            Arrays.copyOfRange(pre,i+1,pre.length),Arrays.copyOfRange(in,i+1,in.length));
        }
    }
    return root;
}

7.用兩個棧來實現一個佇列,完成佇列的Push和Pop操作。 佇列中的元素為int型別。

思路:一個棧壓入元素,而另一個棧作為緩衝,將棧1的元素出棧後壓入棧2中。也可以將棧1中的最後一個元素直接出棧,而不用壓入棧2中再出棧。

程式碼實現:

public void push(int node) {
    stack1.push(node);
}

public int pop() throws Exception {
    if (stack1.isEmpty() && stack2.isEmpty()) {
        throw new Exception("棧為空!");
    }

    if (stack2.isEmpty()) {
        while(!stack1.isEmpty()) {
            stack2.push(stack1.pop());
        }
    }
    return stack2.pop();
}

8.把一個數組最開始的若干個元素搬到陣列的末尾,我們稱之為陣列的旋轉。 輸入一個非遞減排序的陣列的一個旋轉,輸出旋轉陣列的最小元素。 例如陣列{3,4,5,1,2}為{1,2,3,4,5}的一個旋轉,該陣列的最小值為1。 NOTE:給出的所有元素都大於0,若陣列大小為0,請返回0

思路:利用二分法,找到中間的數,然後和最左邊的值進行比較,若大於最左邊的數,則最左邊從mid開始,若小於最右邊值,則最右邊從mid開始。若左中右三值相等,則取mid前後值中較小的數。

程式碼實現:

public int minNumberInRotateArray(int [] array) {
    if (array == null || array.length == 0)
        return 0;
    int left = 0;
    int right = array.length - 1;
    int mid = 0;

    while (array[left] >= array[right]) {
        if(right - left <= 1) {
            mid = right;
            break;
        }
        mid = (left + right)/2;
        if (array[left] == array[mid] && array[mid] == array[right]) {
            if (array[left+1] != array[right-1]) {
                mid = array[left+1] < array[right-1] ? left+1:right-1;
            } else {
              left++;
              right--;
            }
        } else {
          if (array[left] <= array[mid]) {
              left = mid;
          } else {
              right = mid;
          }
        }
    }

    return array[mid];
}

9.1現在要求輸入一個整數n,請你輸出斐波那契數列的第n項。n<=39

思路:遞迴的效率低,使用迴圈方式。

程式碼實現:

public long fibonacci(int n) {
    long result=0;
    long preOne=1;
    long preTwo=0;
    if(n==0) {
        return preTwo;
    }
    if(n==1) {
        return preOne;
    }
    for (int i = 2; i <= n; i++) {
        result = preOne+preTwo;
        preTwo = preOne;
        preOne = result;
    }
    return result;
}

9.2.一隻青蛙一次可以跳上1級臺階,也可以跳上2級。求該青蛙跳上一個n級的臺階總共有多少種跳法。

9.2程式碼與9.1相同

9.3我們可以用2*1的小矩形橫著或者豎著去覆蓋更大的矩形。請問用n個2*1的小矩形無重疊地覆蓋一個2*n的大矩形,總共有多少種方法?

思路:斐波那契數列思想

程式碼實現:

public int Fibonaccik(int n) {
    int number = 1;
    int sum = 1;
    if (n <= 0)
        return 0;
    if (n == 1 ) {
        return 1;
    }

    while (n-- >= 2) {
        sum += number;
        number = sum - number;
    }
    return sum;
}

9.4一隻青蛙一次可以跳上1級臺階,也可以跳上2級……它也可以跳上n級。求該青蛙跳上一個n級的臺階總共有多少種跳法。

思路:2^(n-1)

程式碼實現:

public int JumpFloor2(int target) {
    return (int) Math.pow(2,target-1);
}

10.輸入一個整數,輸出該數二進位制表示中1的個數。其中負數用補碼錶示。

思路:a&(a-1)的結果會將a最右邊的1變為0,直到a = 0,還可以先將a&1 != 0,然後右移1位,但不能計算負數的值,

程式碼實現:

public int NumberOf1(int n) {
    int count = 0;
    while (n != 0) {
        count++;
        n = (n-1) & n;
    }
    return count;
}

未完待續。。。。。