算法題(1)

【程序1】
題目:古典問題:有一對兔子笋妥,從出生后第3個月起每個月都生一對兔子春宣,小兔子長到第三個月后每個月又生一對兔子嫉你,假如兔子都不死幽污,問每個月的兔子總數(shù)為多少?

private static int Fb(int i) {
    //不允許小于0的數(shù)
    if (i <= 0) {
        return -1;
    }

    //Fb(1)=1, Fb(2)=1
    if (i == 1 || i == 2) {
        return 1;
    }

    //遞歸調(diào)用
    return Fb(i-1) + Fb(i-2);
}

public static void main(String[] args) {
    int M=6;   //輸入第幾個月簸搞,自填
    System.out.print("Rabbit total: " + Fb(M));
 }

【程序2】
題目:判斷101-200之間有多少個素數(shù)准潭,并輸出所有素數(shù)。
解析:質數(shù)又稱素數(shù)寺擂。一個大于1的自然數(shù),除了1和它自身外垦细,不能整除其他自然數(shù)的數(shù)叫做質數(shù)挡逼。

public static void main(String[] args) {
    int count = 0;
    for(int i=101; i<=200; i++) {  //遍歷從101到200所有自然數(shù)
        for(int j=2; j < i; j++) {  //從2到i-1遍歷
            if (i%j == 0) {   //除了1和自身外挚瘟,還能被整除饲梭,不是素數(shù)憔涉,跳出內(nèi)循環(huán)。
                break;
            }
            if (j == (i-1)) {  //如果j指針遍歷到i-1穿扳,仍然不能被整除国旷,則認為i是素數(shù)
                count ++;
                System.out.print(i + ", ");
            }
        }
    }
    System.out.print("\nTotal: " + count);
 }

輸出結果:
101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,
Total: 21
算法改進:
第一個對i的for循環(huán)跪但,偶數(shù)肯定不是素數(shù),直接跳過忆首,只遍歷奇數(shù)被环,每次+2;
第二個對j的for循環(huán)浸锨,不需要把i的值完全遍歷悴能,只需要遍歷到i的開平方根即可漠酿,即Math.sqrt(i)。
代碼改進:

public static void main(String[] args) {
    int count = 0;
    for(int i=101; i<=200; i+=2) {  //遍歷從101到200所有奇數(shù)
        boolean flag = true;
        for(int j=2; j <= Math.sqrt(i); j++) {  //從2到sqrt(i)遍歷
            if (i%j == 0) {   //除了1和自身外宇姚,還能被整除,不是素數(shù)阱持,跳出內(nèi)循環(huán)魔熏。
                flag = false;
                break;
            }
        }
        if (flag == true) {
            count ++;
            System.out.print(i + ", ");
        }
    }
    System.out.print("\nTotal: " + count);
 }

【程序3】
快速找出一個數(shù)組中的兩個數(shù)字蒜绽,讓這兩個數(shù)字之和等于一個給定的值、
例如給定一個無序數(shù)組:{3, 7, 10, 4, 9, 2, 5, 6}鼎姊,找出其中兩個數(shù)字之和等于10

//冒泡排序相寇,使其變成一個從小到大的有序序列
private static void bubbleSort(int[] list) {
    int temp;
    for (int i=0; i<list.length; i++) {
        for (int j=list.length-1; j>i; j--) {
            if (list[j] < list[j-1]) {
                temp = list[j-1];
                list[j-1] = list[j];
                list[j] = temp;
            }
        }
    }
}

private static void sum(int[] list) {
    int i = 0;
    int j = list.length-1;
    while (i < j) {
        if (list[i] + list[j] == 10) {
            System.out.print( list[i] + " + " + list[j] + " = 10");
            return;
        } else if (list[i] + list[j] > 10) {
            j --;
        } else if (list[i] + list[j] < 10) {
            i ++;
        }
    }

    System.out.print( "No number equals 10 in array" );
}

public static void main(String[] args) {
    int[] list = {3, 7, 10, 4, 9, 2, 5, 6};
    //排序
    bubbleSort(list);
    //求和
    sum(list);
}

【程序4】一個數(shù)組唤衫,負數(shù)放左邊跺嗽,正數(shù)放右邊
例如:給定數(shù)組{-3, 7, 10, -4, -9, 2, 5, -6}

private static void sort(int[] list) {
    //設置左右指針,i從左遍歷植兰,j從右遍歷
    int i = 0;
    int j = list.length-1;

    //i始終要小于j楣导,否則數(shù)組越界
    while (i < j) {
        //若list[i] 為負數(shù)畜挨,繼續(xù)向右遍歷
        while (i < list.length && list[i] < 0) {
            i ++;
        }

        //若list[i] 為負數(shù),繼續(xù)向左遍歷
        while (j >= 0 && list[j] > 0 ) {
            j --;
        }
        //i始終要小于j
        if (i < j) {
            //正負數(shù)交換
            swap(list, i, j);
        }
    }
}

private static void swap(int[] list, int left, int right) {
    int temp;
    temp = list[right];
    list[right] = list[left];
    list[left] = temp;
}

public static void main(String[] args) {
    int[] list = {-3, 7, 10, -4, -9, 2, 5, -6};
    sort(list);
    for (int i=0; i<list.length; i++) {
        System.out.print( list[i] + ", " );
    }
}

【程序5】找出數(shù)組中重復次數(shù)最多的數(shù),要求時間復雜度O(n)

public static void main(String[] args) {
    int[] arr = {1,1,2,2,3,4,4,4,4,5,5,5,6,6};
    //以arr數(shù)組中的數(shù)作為key逮刨,重復一次value值遞增,最后統(tǒng)計key對應最大的value值
    //即為重復次數(shù)最多的數(shù)
    Map<Integer, Integer> map = new HashMap<Integer, Integer>(  );
    for(int i=0; i<arr.length; i++) {
        if (map.containsKey( arr[i] )) {
            map.put( arr[i], map.get( arr[i] ) + 1 );
        } else {
            map.put( arr[i], 1 );
        }
    }

    //找出map中最大value值對應的key
    Collection<Integer> count = map.values();
    int maxCount = Collections.max( count );
    int maxKey = -1;

    for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
        if (entry.getValue() == maxCount) {
            maxKey = entry.getKey();
        }
    }
    System.out.print( "Number: " + maxKey );
}

【程序6】將兩個排好序的鏈表合并成一個有序鏈表迎罗,要求時間復雜度O(n)

//定義單鏈表片仿,數(shù)據(jù)域data砂豌,next 指針
static class ListNode {
    int data;
    ListNode next;

    public ListNode (int data) {
        this.data = data;
    }
}

public static void main(String[] args) {
    //初始化第一個單鏈表:1->3->7->9
    ListNode list_node = new ListNode( 1 );
    ListNode l2 = new ListNode( 3 );
    list_node.next = l2;
    ListNode l3 = new ListNode( 7 );
    l2.next = l3;
    ListNode l4 = new ListNode( 9 );
    l3.next = l4;
    printListNode(list_node);
    System.out.print( "\n" );

    //初始化第二個單鏈表:2->4->6->8
    ListNode node = new ListNode( 2 );
    ListNode node2 = new ListNode( 4 );
    node.next = node2;
    ListNode node3 = new ListNode( 6 );
    node2.next = node3;
    ListNode node4 = new ListNode( 8 );
    node3.next = node4;
    printListNode(node);
    System.out.print( "\n" );

    ListNode merge = mergingSort(list_node, node);
    printListNode(merge);
}

private static ListNode mergingSort (ListNode listNode1, ListNode listNode2) {
    //如果其中一條鏈表為null阳距,無需合并,直接返回另外一條鏈表
    if (listNode1 == null) {
        return listNode2;
    } else  if (listNode2 == null) {
        return  listNode1;
    }

    //定義一個臨時鏈表存儲
    ListNode mergedNode = new ListNode( 0 );
    ListNode temp = mergedNode;

    //遍歷鏈表1和鏈表2,data更小的數(shù)復制到臨時鏈表中蓄拣,知道其中一個鏈表遍歷完努隙,跳出循環(huán)
    while (listNode1 != null && listNode2 != null) {
        if (listNode1.data <= listNode2.data) {
            temp.next = listNode1;
            listNode1 = listNode1.next;
        } else {
            temp.next = listNode2;
            listNode2 = listNode2.next;
        }
        temp = temp.next;
    }

    //如果其中一條鏈表未遍歷完荸镊,直接合并到臨時鏈表尾部
    if (listNode1 != null) {
        temp.next = listNode1;
    } else  if (listNode2 != null) {
        temp.next = listNode2;
    }
    return  mergedNode.next;
}

//輸出鏈表
private static void printListNode (ListNode node) {
    if (node == null) {
        return;
    }

    while (node != null) {
        System.out.print( node.data );
        node = node.next;
        if (node != null) {
            System.out.print( " -> " );
        }
    }
}

【測序7】打印出所有的 "水仙花數(shù) "躬存,所謂 "水仙花數(shù) "是指一個三位數(shù),其各位數(shù)字立方和等于該數(shù)本身岭洲。例如:153是一個 "水仙花數(shù) "盾剩,因為153=1的三次方+5的三次方+3的三次方。

public static void main(String[] args) {
    int a; //百分位
    int b; //十分位
    int c; //個位
    for (int i=101; i<1000; i++) {
        a = i/100;
        b = (i%100)/10;
        c = (i%100)%10;
        if (i == Math.pow( a, 3 ) + Math.pow( b, 3 ) + Math.pow( c,3 )) {
            System.out.println( i );
        }
    }
}
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市驻粟,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌番挺,老刑警劉巖玄柏,帶你破解...
    沈念sama閱讀 218,755評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件粪摘,死亡現(xiàn)場離奇詭異,居然都是意外死亡苔悦,警方通過查閱死者的電腦和手機椎咧,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評論 3 395
  • 文/潘曉璐 我一進店門勤讽,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人向臀,你說我怎么就攤上這事诸狭⊙庇觯” “怎么了?”我有些...
    開封第一講書人閱讀 165,138評論 0 355
  • 文/不壞的土叔 我叫張陵雀监,是天一觀的道長会前。 經(jīng)常有香客問我匾竿,道長,這世上最難降的妖魔是什么临庇? 我笑而不...
    開封第一講書人閱讀 58,791評論 1 295
  • 正文 為了忘掉前任假夺,我火速辦了婚禮,結果婚禮上梧田,老公的妹妹穿的比我還像新娘侧蘸。我一直安慰自己,他們只是感情好穿稳,可當我...
    茶點故事閱讀 67,794評論 6 392
  • 文/花漫 我一把揭開白布逢艘。 她就那樣靜靜地躺著骤菠,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上截亦,一...
    開封第一講書人閱讀 51,631評論 1 305
  • 那天崩瓤,我揣著相機與錄音踩官,去河邊找鬼。 笑死颖系,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的辩越。 我是一名探鬼主播嘁扼,決...
    沈念sama閱讀 40,362評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼黔攒!你這毒婦竟也來了趁啸?” 一聲冷哼從身側響起强缘,我...
    開封第一講書人閱讀 39,264評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎不傅,沒想到半個月后旅掂,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,724評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡访娶,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了震肮。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片称龙。...
    茶點故事閱讀 40,040評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖戳晌,靈堂內(nèi)的尸體忽然破棺而出鲫尊,到底是詐尸還是另有隱情,我是刑警寧澤沦偎,帶...
    沈念sama閱讀 35,742評論 5 346
  • 正文 年R本政府宣布疫向,位于F島的核電站,受9級特大地震影響豪嚎,放射性物質發(fā)生泄漏搔驼。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,364評論 3 330
  • 文/蒙蒙 一侈询、第九天 我趴在偏房一處隱蔽的房頂上張望舌涨。 院中可真熱鬧,春花似錦扔字、人聲如沸囊嘉。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽扭粱。三九已至,卻和暖如春震檩,著一層夾襖步出監(jiān)牢的瞬間琢蛤,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評論 1 270
  • 我被黑心中介騙來泰國打工抛虏, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留博其,地道東北人。 一個月前我還...
    沈念sama閱讀 48,247評論 3 371
  • 正文 我出身青樓迂猴,卻偏偏與公主長得像贺奠,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子错忱,可洞房花燭夜當晚...
    茶點故事閱讀 44,979評論 2 355

推薦閱讀更多精彩內(nèi)容