狭义的贪心
每一步做出在当前状态下的最好或者最优的选择,从而希望最终的结果是最好或者最优的算法
题目一
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
public static String largestNumber(int[] nums) { int n = nums.length; String[] strs = new String[n]; for (int i = 0; i < n; i++) { strs[i] = String.valueOf(nums[i]); } Arrays.sort(strs, (a, b) -> (b + a).compareTo(a + b)); if (strs[0].equals("0")) { return "0"; } StringBuilder path = new StringBuilder(); for (String s : strs) { path.append(s); } return path.toString(); }
|
题目二
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class Solution {
public static int twoCitySchedCost(int[][] costs) { int n = costs.length; int[] arr = new int[n]; int sum = 0; for (int i = 0; i < n; i++) { arr[i] = costs[i][1] - costs[i][0]; sum += costs[i][0]; } Arrays.sort(arr); int m = n / 2; for (int i = 0; i < m; i++) { sum += arr[i]; } return sum; } }
|