判斷鏈表有環(huán)
public class LinkedListCycle {/*** 判斷是否有環(huán)* @param head 鏈表頭節(jié)點*/public static boolean isCycle(Node head) {Node p1 = head;Node p2 = head;while (p2!=null && p2.next!=null){p1 = p1.next;p2 = p2.next.next;if(p1 == p2){return true;}}return false;}/*** 鏈表節(jié)點*/private static class Node {int data;Node next;Node(int data) {this.data = data;}}public static void main(String[] args) throws Exception {Node node1 = new Node(5);Node node2 = new Node(3);Node node3 = new Node(7);Node node4 = new Node(2);Node node5 = new Node(6);node1.next = node2;node2.next = node3;node3.next = node4;node4.next = node5;node5.next = node2;System.out.println(isCycle(node1));}
}
最小數(shù)棧
import java.util.Stack;public class MinStack {private Stack<Integer> mainStack = new Stack<Integer>();private Stack<Integer> minStack = new Stack<Integer>();/*** 入棧操作* @param element 入棧的元素*/public void push(int element) {mainStack.push(element);//如果輔助棧為空,或新元素小于等于輔助棧棧頂,則新元素壓入輔助棧if (minStack.empty() || element <= minStack.peek()) {minStack.push(element);}}/*** 出棧操作*/public Integer pop() {//如果出棧元素和輔助棧棧頂元素值相等,輔助棧出棧if (mainStack.peek().equals(minStack.peek())) {minStack.pop();}return mainStack.pop();}/*** 獲取棧的最小元素*/public int getMin() throws Exception {if (mainStack.empty()) {throw new Exception("stack is empty");}return minStack.peek();}public static void main(String[] args) throws Exception {MinStack stack = new MinStack();stack.push(4);stack.push(9);stack.push(7);stack.push(3);stack.push(8);stack.push(5);System.out.println(stack.getMin());stack.pop();stack.pop();stack.pop();System.out.println(stack.getMin());}
}
最大公約數(shù)
public class GreatestCommonDivisor {public static int getGreatestCommonDivisor(int a, int b){int big = a>b ? a:b;int small = a<b ? a:b;if(big%small == 0){return small;}for(int i= small/2; i>1; i--){if(small%i==0 && big%i==0){return i;}}return 1;}public static int getGreatestCommonDivisorV2(int a, int b){int big = a>b ? a:b;int small = a<b ? a:b;if(big%small == 0){return small;}return getGreatestCommonDivisorV2(big%small, small);}public static int getGreatestCommonDivisorV3(int a, int b){if(a == b){return a;}int big = a>b ? a:b;int small = a<b ? a:b;return getGreatestCommonDivisorV3(big - small, small);}public static int gcd(int a, int b){if(a == b){return a;}if((a&1)==0 && (b&1)==0){return gcd(a >> 1, b >> 1)<<1;} else if((a&1)==0 && (b&1)!=0){return gcd(a >> 1, b);} else if((a&1)!=0 && (b&1)==0){return gcd(a, b >> 1);} else {int big = a>b ? a:b;int small = a<b ? a:b;return gcd(big - small, small);}}public static void main(String[] args) {System.out.println(gcd(25, 5));System.out.println(gcd(100, 80));System.out.println(gcd(27, 14));}
}
2的冪
public class PowerOf2 {public static boolean isPowerOf2(int num) {int temp = 1;while(temp<=num){if(temp == num){return true;}temp = temp*2;}return false;}public static boolean isPowerOf2V2(int num) {int temp = 1;while(temp<=num){if(temp == num){return true;}temp = temp<<1;}return false;}public static boolean isPowerOf2V3(int num) {return (num&num-1) == 0;}public static void main(String[] args) {System.out.println(isPowerOf2V3(32));System.out.println(isPowerOf2V3(19));}
}
最大有序距離
public class MaxSortedDistance {public static int getMaxSortedDistance(int[] array){//1.得到數(shù)列的最大值和最小值int max = array[0];int min = array[0];for(int i=1; i<array.length; i++) {if(array[i] > max) {max = array[i];}if(array[i] < min) {min = array[i];}}int d = max - min;//如果max和min相等,說明數(shù)組所有元素都相等,返回0if(d == 0){return 0;}//2.初始化桶int bucketNum = array.length;Bucket[] buckets = new Bucket[bucketNum];for(int i = 0; i < bucketNum; i++){buckets[i] = new Bucket();}//3.遍歷原始數(shù)組,確定每個桶的最大最小值for(int i = 0; i < array.length; i++){//確定數(shù)組元素所歸屬的桶下標int index = ((array[i] - min) * (bucketNum-1) / d);if(buckets[index].min==null || buckets[index].min>array[i]){buckets[index].min = array[i];}if(buckets[index].max==null || buckets[index].max<array[i]){buckets[index].max = array[i];}}//4.遍歷桶,找到最大差值int leftMax = buckets[0].max;int maxDistance = 0;for (int i=1; i<buckets.length; i++) {if (buckets[i].min == null) {continue;}if (buckets[i].min - leftMax > maxDistance) {maxDistance = buckets[i].min - leftMax;}leftMax = buckets[i].max;}return maxDistance;}/*** 桶*/private static class Bucket {Integer min;Integer max;}public static void main(String[] args) {int[] array = new int[] {2,6,3,4,5,10,9};System.out.println(getMaxSortedDistance(array));}
}
用棧實現(xiàn)隊列
import java.util.Stack;public class StackQueue {private Stack<Integer> stackA = new Stack<Integer>();private Stack<Integer> stackB = new Stack<Integer>();/*** 入隊操作* @param element 入隊的元素*/public void enQueue(int element) {stackA.push(element);}/*** 出隊操作*/public Integer deQueue() {if(stackB.isEmpty()){if(stackA.isEmpty()){return null;}transfer();}return stackB.pop();}/*** 棧A元素轉移到棧B*/private void transfer(){while (!stackA.isEmpty()){stackB.push(stackA.pop());}}public static void main(String[] args) throws Exception {StackQueue stackQueue = new StackQueue();stackQueue.enQueue(1);stackQueue.enQueue(2);stackQueue.enQueue(3);System.out.println(stackQueue.deQueue());System.out.println(stackQueue.deQueue());stackQueue.enQueue(4);System.out.println(stackQueue.deQueue());System.out.println(stackQueue.deQueue());}
}
最近數(shù)字
import java.util.Arrays;public class FindNearestNumber {public static int[] findNearestNumber(int[] numbers){//1.從后向前查看逆序區(qū)域,找到逆序區(qū)域的前一位,也就是數(shù)字置換的邊界int index = findTransferPoint(numbers);//如果數(shù)字置換邊界是0,說明整個數(shù)組已經(jīng)逆序,無法得到更大的相同數(shù)字組成的整數(shù),返回nullif(index == 0){return null;}//2.把逆序區(qū)域的前一位和逆序區(qū)域中剛剛大于它的數(shù)字交換位置//拷貝入?yún)?#xff0c;避免直接修改入?yún)nt[] numbersCopy = Arrays.copyOf(numbers, numbers.length);exchangeHead(numbersCopy, index);//3.把原來的逆序區(qū)域轉為順序reverse(numbersCopy, index);return numbersCopy;}private static int findTransferPoint(int[] numbers){for(int i=numbers.length-1; i>0; i--){if(numbers[i] > numbers[i-1]){return i;}}return 0;}private static int[] exchangeHead(int[] numbers, int index){int head = numbers[index-1];for(int i=numbers.length-1; i>0; i--){if(head < numbers[i]){numbers[index-1] = numbers[i];numbers[i] = head;break;}}return numbers;}private static int[] reverse(int[] num, int index){for(int i=index,j=num.length-1; i<j; i++,j--){int temp = num[i];num[i] = num[j];num[j] = temp;}return num;}public static void main(String[] args) {int[] numbers = {1,2,3,4,5};//打印12345之后的10個全排列整數(shù)for(int i=0; i<10;i++){numbers = findNearestNumber(numbers);outputNumbers(numbers);}}//輸出數(shù)組private static void outputNumbers(int[] numbers){for(int i : numbers){System.out.print(i);}System.out.println();}
}
刪除整數(shù)的k個數(shù)字,獲得刪除后的最小值
public class RemoveKDigits {/*** 刪除整數(shù)的k個數(shù)字,獲得刪除后的最小值* @param num 原整數(shù)* @param k 刪除數(shù)量*/public static String removeKDigits(String num, int k) {for(int i=0; i<k; i++){boolean hasCut = false;//從左向右遍歷,找到比自己右側數(shù)字大的數(shù)字并刪除for(int j=0; j<num.length()-1;j++){if(num.charAt(j) > num.charAt(j+1)){num = num.substring(0, j) + num.substring(j+1,num.length());hasCut = true;break;}}//如果沒有找到要刪除的數(shù)字,則刪除最后一個數(shù)字if(!hasCut){num = num.substring(0, num.length()-1);}}//清除整數(shù)左側的數(shù)字0int start = 0;for(int j=0; j<num.length()-1; j++){if(num.charAt(j) != '0'){break;}start++;}num = num.substring(start, num.length()) ;//如果整數(shù)的所有數(shù)字都被刪除了,直接返回0if(num.length() == 0){return "0";}return num;}/*** 刪除整數(shù)的k個數(shù)字,獲得刪除后的最小值* @param num 原整數(shù)* @param k 刪除數(shù)量*/public static String removeKDigitsV2(String num, int k) {//新整數(shù)的最終長度 = 原整數(shù)長度 - kint newLength = num.length() - k;//創(chuàng)建一個棧,用于接收所有的數(shù)字char[] stack = new char[num.length()];int top = 0;for (int i = 0; i < num.length(); ++i) {//遍歷當前數(shù)字char c = num.charAt(i);//當棧頂數(shù)字大于遍歷到的當前數(shù)字,棧頂數(shù)字出棧(相當于刪除數(shù)字)while (top > 0 && stack[top-1] > c && k > 0) {top -= 1;k -= 1;}//如果遇到數(shù)字0,且棧為空,0不入棧if('0' == c && top == 0){newLength--;if(newLength <= 0){return "0";}continue;}//遍歷到的當前數(shù)字入棧stack[top++] = c;}// 用棧構建新的整數(shù)字符串return newLength<=0 ? "0" : new String(stack, 0, newLength);}public static void main(String[] args) {System.out.println(removeKDigits("1593212", 3));System.out.println(removeKDigits("30200", 1));System.out.println(removeKDigits("10", 2));System.out.println(removeKDigits("541270936", 3));System.out.println(removeKDigits("1593212", 4));System.out.println(removeKDigits("1000020000000010", 2));}
}
大整數(shù)求和
public class BigNumberSum {/*** 大整數(shù)求和* @param bigNumberA 大整數(shù)A* @param bigNumberB 大整數(shù)B*/public static String bigNumberSum(String bigNumberA, String bigNumberB) {//1.把兩個大整數(shù)用數(shù)組逆序存儲,數(shù)組長度等于較大整數(shù)位數(shù)+1int maxLength = bigNumberA.length() > bigNumberB.length() ? bigNumberA.length() : bigNumberB.length();int[] arrayA = new int[maxLength+1];for(int i=0; i< bigNumberA.length(); i++){arrayA[i] = bigNumberA.charAt(bigNumberA.length()-1-i) - '0';}int[] arrayB = new int[maxLength+1];for(int i=0; i< bigNumberB.length(); i++){arrayB[i] = bigNumberB.charAt(bigNumberB.length()-1-i) - '0';}//2.構建result數(shù)組,數(shù)組長度等于較大整數(shù)位數(shù)+1int[] result = new int[maxLength+1];//3.遍歷數(shù)組,按位相加for(int i=0; i<result.length; i++){int temp = result[i];temp += arrayA[i];temp += arrayB[i];//判斷是否進位if(temp >= 10){temp = temp-10;result[i+1] = 1;}result[i] = temp;}//4.把result數(shù)組再次逆序并轉成StringStringBuilder sb = new StringBuilder();//是否找到大整數(shù)的最高有效位boolean findFirst = false;for (int i = result.length - 1; i >= 0; i--) {if(!findFirst){if(result[i] == 0){continue;}findFirst = true;}sb.append(result[i]);}return sb.toString();}public static void main(String[] args) {System.out.println(bigNumberSum("426709752318", "95481253129"));}
}
獲得金礦最優(yōu)收益
public class GoldMining {/*** 獲得金礦最優(yōu)收益* @param w 工人數(shù)量* @param p 金礦開采所需工人數(shù)量* @param g 金礦儲量*/public static int getBestGoldMiningV3(int w, int[] p, int[] g){//創(chuàng)建當前結果int[] results = new int[w+1];//填充一維數(shù)組for(int i=1; i<=g.length; i++){for(int j=w; j>=1; j--){if(j>=p[i-1]){results[j] = Math.max(results[j], results[j-p[i-1]]+ g[i-1]);}}}//返回最后一個格子的值return results[w];}/*** 獲得金礦最優(yōu)收益* @param w 工人數(shù)量* @param p 金礦開采所需工人數(shù)量* @param g 金礦儲量*/public static int getBestGoldMiningV2(int w, int[] p, int[] g){//創(chuàng)建表格int[][] resultTable = new int[g.length+1][w+1];//填充表格for(int i=1; i<=g.length; i++){for(int j=1; j<=w; j++){if(j<p[i-1]){resultTable[i][j] = resultTable[i-1][j];}else{resultTable[i][j] = Math.max(resultTable[i-1][j], resultTable[i-1][j-p[i-1]]+ g[i-1]);}}}//返回最后一個格子的值return resultTable[g.length][w];}/*** 獲得金礦最優(yōu)收益* @param w 工人數(shù)量* @param n 可選金礦數(shù)量* @param p 金礦開采所需工人數(shù)量* @param g 金礦儲量*/public static int getBestGoldMining(int w, int n, int[] p, int[] g){if(w==0 || n==0){return 0;}if(w<p[n-1]){return getBestGoldMining(w, n-1, p, g);}return Math.max(getBestGoldMining(w, n-1, p, g), getBestGoldMining(w-p[n-1], n-1, p, g)+g[n-1]);}public static void main(String[] args) {int w = 10;int[] p = {5, 5, 3, 4 ,3};int[] g = {400, 500, 200, 300 ,350};System.out.println("最優(yōu)收益:" + getBestGoldMining(w, g.length, p, g));}}
找到缺失的數(shù)字
public class FindLostNum {public static int[] findLostNum(int[] array) {//用于存儲兩個出現(xiàn)奇數(shù)次的整數(shù)int result[] = new int[2];//第一次整體異或int xorResult = 0;for(int i=0;i<array.length;i++){xorResult^=array[i];}//如果異或結果為0,說明輸入數(shù)組不符合題目if(xorResult == 0){return null;}//確定兩個整數(shù)的不同位,以此來做分組int separator = 1;while (0==(xorResult&separator)){separator<<=1;}//第二次分組異或for(int i=0;i<array.length;i++){if(0==(array[i]&separator)){result[0]^=array[i];}else {result[1]^=array[i];}}return result;}public static void main(String[] args) {int[] array = {4,1,2,2,5,1,4,3};int[] result = findLostNum(array);System.out.println(result[0] + "," + result[1]);}
}
總結
以上是生活随笔為你收集整理的《漫画算法》源码整理-6的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內容還不錯,歡迎將生活随笔推薦給好友。