題目描述java
/** * 有序數組去重 * 輸出最終的數字個數 * 輸入:1,2,2 * 輸出:2 * @author Turing * */
代碼數組
import java.util.*; public class E { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String[] str = sc.nextLine().split(","); int len = str.length; int [] array = new int[len]; for (int i = 0; i < len; i++) { array[i] = Integer.valueOf(str[i]); } int index = 1; for (int i = 0; i < len-1; i++) { if(array[i]!=array[i+1]){ array[index] = array[i+1]; index++; } } System.out.println(index); } }
題目描述spa
/** * 分糖果問題相似 * 分餅乾問題,每一個孩子至少一個餅乾, * 若是兩個孩子坐一塊兒,評分高的孩子必須獲得更多的餅乾(左右都比較) * 輸出老師購買餅乾總數的最小值 * 輸入: 6 3 6 3 5 6 2 * 輸出: 10 * 說明:第一個數表示孩子數爲6;1+2+1+2+3+1=10 */
代碼code
import java.util.*; public class E4 { public static int m; public static int n; public static void main(String[] args) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); int[] score = new int[n]; int[] count = new int[n]; for (int i = 0; i < n; i++) { score[i] = sc.nextInt(); } Arrays.fill(count, 1); for(int i=1; i<n; i++){ if (score[i]>score[i-1]) { count[i]=count[i-1]+1; } } for(int i=n-2; i>=0; i--){ if (score[i]>score[i+1] && count[i]<=count[i+1]) { count[i]=Math.max(count[i], count[i+1]+1); } } int sum = 0; for (int i = 0; i < count.length; i++) { sum += count[i]; } System.out.println(sum); } }
題目描述blog
/** * 有一個地圖,圍棋棋盤,兩點之間有行走距離起點爲左上角,終點爲右下角在地圖上, * 每次行走只能沿線移動到移動的臨近的點 * 並累加路徑計算一我的從地圖的起點走到終點的最小路徑爲多少? * 輸入: * m*n地圖表示以下: * 3 * 3 * 1 3 4 * 2 1 2 * 4 3 1 * 其中 m=3,n=3表示3*3矩陣 * 行走路徑爲: 下》右》右》下 * 路徑總長:1+2+1+2+1=7 * * @author Turing * */
代碼leetcode
import java.util.*;
public class E4 { public static int m; public static int n; public static void main(String[] args) { Scanner sc = new Scanner(System.in); m = sc.nextInt(); n = sc.nextInt(); int [][] grid = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { grid[i][j] = sc.nextInt(); } } System.out.println(minpath(grid, 0, 0)); } public static int minpath(int[][]grid, int i,int j){ if(i==m||j==n){ return Integer.MAX_VALUE; } if(i==m-1&&j==n-1){ return grid[i][j]; } return grid[i][j]+Math.min(minpath(grid, i+1, j), minpath(grid, i, j+1)); } }