We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
JavaScript实现leetcode 945. 使数组唯一的最小增量
第一种:暴力解决 用数组统计每个数出现的次数,每次递增1,直到增加到一个没有重复出现过得数字位置。这种时间复杂度大,可以为 O(n^2)
第二种:排序
直接用排序实现。
/** * @param {number[]} A * @return {number} */ var minIncrementForUnique = function(A) { A.sort((a, b) => a - b); const queue = []; let result = 0; let prev = A[0] - 1; for(let i = 0; i < A.length; i++) { if(A[i] === prev) { queue.push(A[i]); } else if(A[i] === prev + 1) { prev++; } else { // 队列不为空,则需要先处理队列中的值 if(queue.length) { const n = queue.shift(); // 直接更新到要更新的值 result += prev + 1 - n; // 每次加1 prev++; // 队列不为空,因此还是保留在当前值,而不往后遍历 i--; } else { prev = A[i]; } } } // 队列不为空,则可以将剩下的值依次递增为 [prev+1,∞)中的数字,prev代表数组的最后一个值。 while(queue.length) { const n = queue.shift(); result += prev + 1 - n; prev++; } return result; };
The text was updated successfully, but these errors were encountered:
No branches or pull requests
JavaScript实现leetcode 945. 使数组唯一的最小增量
题目描述
思路分析
第一种:暴力解决
用数组统计每个数出现的次数,每次递增1,直到增加到一个没有重复出现过得数字位置。这种时间复杂度大,可以为 O(n^2)
第二种:排序
解题方法
直接用排序实现。
The text was updated successfully, but these errors were encountered: