java實現9道簡單算法題

   //【1】**********************************************************************************************
    /**
     * 將一個三位數反轉
     * @param number
     * @return
     */
    public int reverseNumber(int number) {
        System.out.println("=== start: 將一個三位數反轉");
        //驗證三位數
        int wholeNumber = number / 100;
        if (wholeNumber == 0 ||  wholeNumber > 9 ) {
            System.out.println("不是三位數,請從新輸入");
            return -1;
        }
        //方法一:利用String,charArr,Integer相互轉化的函數;2.兩個位置臨時交換
        String digitalStr = String.valueOf(number);
        char[] charArr = digitalStr.toCharArray();
        char charOne = charArr[0];
        charArr[0] = charArr[2];
        charArr[2] = charOne;
        int resultDigital = Integer.valueOf(String.valueOf(charArr));
        System.out.println("result: " + resultDigital);
        return resultDigital;

        //TODO 方法二:繼續完善,不用String包裝類
    }

    //【2】**********************************************************************************************
    /**
     *   將一個小寫本身轉爲大寫字母
     */
    public char lowercaseToUppercase(char character) {
        System.out.println("=== start: 將一個小寫本身轉爲大寫字母");
        System.out.println("input: " + character);
        //判斷小寫字符

        //方法一:
        // 根據條件,轉換成對應的大小寫
        String s = String.valueOf(character);
        char resultChar = s.toUpperCase().toCharArray()[0];

        //TODO:方法二:
        //根據ascii值

        System.out.println("result: " + resultChar);
        return resultChar;
    }

    //【3】**********************************************************************************************
    /**
     * 發現斐波那契中第N個數
     * @param n
     * @return
     */
    public int findNFibonaci(int n) {
        System.out.println("=== start: 發現斐波那契中第N個數");
        int first = 0;
        int second = 1;
        int third = -1;
        if (n <=  0) {

        } else if (n == 1) {//寫錯了,寫成了if( i==1 )
            third = first;
        } else if (n == 2) {
            third = second;
        } else {
            for (int i = 3; i <= n; i++) {
                    third = first + second;
                    first = second;
                    second = third;
                System.out.println("第"+ i +"位: " + third);
            }
        }
        System.out.println("result: " + third);
        return third;
    }

    //【4】**********************************************************************************************
    /**
     * https://lintcode.com/problem/remove-linked-list-elements/description
     * 刪除鏈表中等於給定值val的全部節點。
     */
    //Definition for ListNode
    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }

        @Override
        public String toString() {
            StringBuffer stringBuffer = new StringBuffer();
            ListNode nowNode = this;
            while (nowNode != null) {
                stringBuffer.append(nowNode.val + "->");
                nowNode = nowNode.next;
            }
            return stringBuffer.toString();
        }
    }

    /**
     * @param head: a ListNode
     * @param val: An integer
     * @return: a ListNode
     */
    public ListNode removeElements(ListNode head, int val) {
        if (head == null)
            return null;
         //方法1:前一個(n-1)節點的next指向n+1個節點
         ListNode nowNode = head;
         ListNode preNode = null;
         ListNode validNode = null;
         ListNode preValidNode = null;
         while(nowNode != null) {
            if (nowNode.val == val) {
//                if (preNode == null) {
//                } else {
//                    preNode.next = nowNode.next;
//                }
                if (preNode == null) {
                    preNode = nowNode;
                } else {
                    preNode.next = nowNode.next;
                }
            } else {
//                if (preValidNode == null) {
//                    preValidNode = nowNode;
//                } else {
//                    preValidNode.next = nowNode;
//                    preValidNode = nowNode;
//                }

//                if (validNode == null) {
//                    validNode = nowNode;
//                } else {
//                    validNode.next = nowNode;
//                    preNode = nowNode;
//                }
                preNode = nowNode;
            }

            nowNode = nowNode.next;
         }
        //處理第一個節點

        if(head.val == val) {
             head = head.next;
        }

        //方法2???:建立新的鏈表,只有記錄新的節點

        return head;
    }

    /**
     * 實例:
     * 1.  1-2-3-4   刪除 2,3,4(簡單); 刪除1(比較難)
     * 1.  1-2-3-3-4-3   刪除 3(簡單)
     */
    private void testRemoveElements() {

        ListNode resultNode = new ListNode(1);
        ListNode next2 = new ListNode(2);
        resultNode.next = next2;

        ListNode next3 = new ListNode(3);
        next2.next = next3;

        ListNode next4 = new ListNode(4);
        next3.next = next4;
        System.out.println("primary: " + resultNode.toString() + ";val:" + 1);
        ListNode result = removeElements(resultNode, 1);
        System.out.println("result: " + result.toString());

        //case2:
        ListNode resultNode2 = new ListNode(1);
        ListNode next22 = new ListNode(2);
        resultNode2.next = next22;

        ListNode next23 = new ListNode(3);
        next22.next = next23;

        ListNode next24 = new ListNode(3);
        next23.next = next24;

        ListNode next25 = new ListNode(4);
        next24.next = next25;

        ListNode next26 = new ListNode(3);
        next25.next = next26;
        System.out.println("primary2: " + resultNode2.toString()  + ";val:" + 3);
        ListNode result2 = removeElements(resultNode2, 3);
        System.out.println("result2: " + result2.toString());

        //case 3
        ListNode resultNode3 = new ListNode(1);
        ListNode next32 = new ListNode(1);
        resultNode3.next = next32;

        ListNode next33 = new ListNode(1);
        next32.next = next33;

        ListNode next34 = new ListNode(4);
        next33.next = next34;
        System.out.println("primary3: " + resultNode3.toString()  + ";val:" + 1);
        ListNode result3 = removeElements(resultNode3, 1);
        System.out.println("result3: " + result3.toString());
    }

   //【5】**********************************************************************************************
    /**
     * 實現一個矩陣類Rectangle,包含以下的一些成員變量與函數:

     兩個共有的成員變量 width 和 height 分別表明寬度和高度。
     一個構造函數,接受2個參數 width 和 height 來設定矩陣的寬度和高度。
     一個成員函數 getArea,返回這個矩陣的面積。
     */
    public class Rectangle {
        private int width;
        private int height;
        public Rectangle(int width, int height) {
            this.width = width;
            this.height = height;
        }

        public int getArea() {
            int area = width * height;
            return area;
        }
    }

    public void testRectangle() {
        Rectangle rec = new Rectangle(3, 4);
        int area = rec.getArea(); // should get 12
        System.out.println("primary: width-3,height:4;area?");
        System.out.println("result: " + area);
    }

    //【6】******************************************************************************************
    /**
     * 給一組整數,按照升序排序,使用選擇排序,冒泡排序,插入排序或者任何 O(n2) 的排序算法。
     * 總結:排序和查找是兩種操做。
     * @param A: an integer array
     * @return: nothing
     */
    public void sortIntegers(int[] A) {
        // 冒泡排序:---小的冒泡
        if (A == null || A.length <= 1) {
            return;
        }
        int size = A.length;
        System.out.println();
        System.out.print("[");
        for(int i = 0; i < size; i++) {
            System.out.print(" " + A[i]);
        }
        System.out.print("]");
        int exchangeCount = 1;
        int count = 0;
        while (exchangeCount > 0){
            exchangeCount = 0;
            for(int j = 0; j < size -1; j++) {
                if (A[j] > A[j+1]) {
                    int temp = A[j];
                    A[j] = A[j+1];
                    A[j+1] = temp;
                    exchangeCount++;
                }
            }
            count++;
        }
        System.out.println("count:" + count);
        System.out.print("[");
        for(int i = 0; i < size; i++) {
          System.out.print(" " + A[i]);
        }
        System.out.print("]");
        // 選擇排序

        // 插入排序???
    }

    public void sortIntegersByChoose(int[] A) {
        // 選擇排序
        if (A == null || A.length <= 1) {
            return;
        }

        int size = A.length;

        //log
        System.out.println();
        System.out.print("[");
        for(int i = 0; i < size; i++) {
            System.out.print(" " + A[i]);
        }
        System.out.print("]");

        int curIndex;
        int minIndex;
        for(int i = 0; i < size - 1; i++) { //循環次數:5次
            curIndex = i; //概念
            minIndex = curIndex;
            for(int j = curIndex + 1; j < size; j++) { //循環次數:4,3,2,1
                if (A[minIndex] > A[j]) {
                    minIndex = j;
                }
            }

            if (minIndex != curIndex) {
               int temp = A[curIndex];
               A[curIndex] = A[minIndex];
               A[minIndex] = temp;
            }
        }

        //log
        System.out.println();
        System.out.print("[");
        for(int i = 0; i < size; i++) {
            System.out.print(" " + A[i]);
        }
        System.out.print("]");
    }

    public void sortIntegersByInsert(int[] A) {
        // 插入排序:---插入已經排好序的數組中
        if (A == null || A.length < 1) {
            return;
        }
        int size = A.length;
        //log
        System.out.println();
        System.out.print("[");
        for(int i = 0; i < size; i++) {
            System.out.print(" " + A[i]);
        }
        System.out.println("]");

        int changeCount = 0;
        int reverseCount = 0;
        for(int i = 1; i < size;i++) {
            int tempIndex = i - 1;
            for(int j = tempIndex; j >= 0; j--) {
                reverseCount++;
                if(A[j+1] < A[j]) {
                    int tempVal = A[j+1];
                    A[j+1] = A[j];
                    A[j] = tempVal;
                    changeCount++;
                } else {
                    break;
                }
            }
        }

        System.out.println("changeCount: " + changeCount);
        System.out.println("reverseCount: " + reverseCount);
        System.out.print("[");
        for(int i = 0; i < size; i++) {
            System.out.print(" " + A[i]);
        }
        System.out.println("]");
    }

    private void testSort() {
        //case 1
        int[] intArr = new int[]{4,3,2,5,1};
        sortIntegers(intArr);

        //case 2
        int[] intArr1 = new int[]{4,3,2,5,1, 8,2};
        sortIntegers(intArr1);

        //case 3
        int[] intArr2 = new int[]{1,2,3,4,5,6};
        sortIntegers(intArr2);
    }

    private void testSortByChoose() {
        //case 1
        int[] intArr = new int[]{4,3,2,5,1};
        sortIntegersByChoose(intArr);

        //case 2
        int[] intArr1 = new int[]{4,3,2,5,1, 8,2};
        sortIntegersByChoose(intArr1);

        //case 3
        int[] intArr2 = new int[]{1,2,3,4,5,6};
        sortIntegersByChoose(intArr2);
    }

    private void testSortByInsert() {
        //case 1
        int[] intArr = new int[]{4,3,2,5,1};
        sortIntegersByInsert(intArr);

        //case 2
        int[] intArr1 = new int[]{4,3,2,5,1, 8,2};
        sortIntegersByInsert(intArr1);

        //case 3
        int[] intArr2 = new int[]{1,2,3,4,5,6};
        sortIntegersByInsert(intArr2);
    }

    //【7】*****************************************************************************
    /**
     *  鏈表節點計數
     *  描述
     *  計算鏈表中有多少個節點
     * @param head
     * @return
     */
    public int countNodes(ListNode head) {
        // write your code here
        int count = 0;
        while (head != null) {
            count++;
            head = head.next;
        }
        System.out.println("countNodes:" + count);
        return count;
    }

    private void testCountNodes() {
        //case 1
        ListNode resultNode = new ListNode(1);
        ListNode next2 = new ListNode(2);
        resultNode.next = next2;

        ListNode next3 = new ListNode(3);
        next2.next = next3;

        ListNode next4 = new ListNode(4);
        next3.next = next4;

        countNodes(resultNode);
        countNodes(next3);
        countNodes(next4);
        countNodes(next4.next);
    }

    //【8】**********************************************************************************************
    /**
        數組第二大數
        在數組中找到第二大的數
        方法:選擇排序最簡單
     */
    public int secondMax(int[] nums) {
        // write your code here
        if(nums == null || nums.length == 0 || nums.length == 1) {
            return -1;
        }

        int size = nums.length;
        int reverseCount = 2;
        if (size == 2 ) {
            reverseCount = 1;
        }
        for(int i = 0; i < reverseCount; i++) {
            int maxIndex = i;
            for(int j = i + 1; j < size; j++) {
                if (nums[maxIndex] < nums[j]){
                    maxIndex = j;
                }
            }

            if (maxIndex != i) {
                int tempVal = nums[maxIndex];
                nums[maxIndex] = nums[i];
                nums[i] = tempVal;
            }
        }
        return nums[1];
    }

    public void testSecondMax() {
        int[] intArr1 = new int[]{3,1,4,2,5};
        int secondMax = secondMax(intArr1);
        System.out.println("secondMax:" + secondMax);
    }

    //【9】**********************************************************************************************
    /**
        交換數組兩個元素---【入門】
        給你一個數組和兩個索引,交換下標爲這兩個索引的數字
        樣例
        給出 [1,2,3,4] index1 = 2, index2 = 3. 交換以後變成 [1,2,4,3]
     */
    public void swapIntegers(int[] A, int index1, int index2) {
        if (A == null || A.length == 0 || index1 == index2 || index1 < 0 || index2 < 0
                || index1 >= A.length || index2 >= A.length) {
            return;
        }

        System.out.println("origin array:");
        for(int i = 0; i < A.length; i++) {
            System.out.print(A[i] + " ");
        }

        System.out.println();
        System.out.println("swapIndex: " + index1 + " " + index2);

        int tempVal = A[index1];
        A[index1] = A[index2];
        A[index2] = tempVal;

        System.out.println("new array:");
        for(int i = 0; i < A.length; i++) {
            System.out.print(A[i] + " ");
        }
    }

    public void testSwapInteger() {
        int[] intArr1 = new int[]{3,1,4,2,5};
        swapIntegers(intArr1, 1,2);
    }
相關文章
相關標籤/搜索