package leetcode; import java.util.Arrays; /** * Created by w84108989 on 2019/1/11. */ //给定整数数组 A,每次 move 操作将会选择任意 A[i],并将其递增 1。 // // 返回使 A 中的每个值都是唯一的最少操作次数。 // // 示例 1: // // 输入:[1,2,2] // 输出:1 // 解释:经过一次 move 操作,数组将变为 [1, 2, 3]。 // 示例 2: // // 输入:[3,2,1,2,1,7] // 输出:6 // 解释:经过 6 次 move 操作,数组将变为 [3, 4, 1, 2, 5, 7]。 // 可以看出 5 次或 5 次以下的 move 操作是不能让数组的每个值唯一的。 public class add_min_945 { public static void main(String[] args) { int a[] = {3,2,1,2,1,7}; int b[] = {1,8,8}; int c[] = {2,1,5}; System.out.println(minIncrementForUnique(c)); System.out.println(minIncrementForUnique(b)); System.out.println(minIncrementForUnique(a)); } public static int minIncrementForUnique(int[] A) { if (A.length == 0){ return 0; } Arrays.sort(A); int res = 0; for (int i = 1; i < A.length; i++) { if(A[i] <= A[i-1]){ res += A[i-1] + 1 - A[i]; A[i] = A[i-1] + 1; } } return res; } }
leetcode_945
最新推荐文章于 2022-04-17 16:18:54 发布