C# public class Solution { public int NextGreaterElement(int n) { char[] nums = n.ToString().ToCharArray(); int i = nums.Length - 2; while (i >= 0 && nums[i] >= nums[i + 1]) { i--; } if (i < 0) { return -1; } int j = nums.Length - 1; while (j >= 0 && ...
class Solution { ListNode *head; public: Solution(ListNode *head) { this->head = head; } int getRandom() { int i = 1, ans = 0; for (auto node = head; node; node = node->next) { if (rand() % i == 0) { // 1/i 的概率选中(替换为答案) ans = node->val; } ++i; ...
classSolution{// 存储最终结果的二维数组,每个子数组是一个排列vector<vector<int>>ret;// 当前递归路径,用于构建一个排列vector<int>path;// 标记数组,用于记录 nums 中的元素是否被使用过bool check[7];// 假设 nums.size() 最大为 7,实际可用动态数组优化public:vector<vector<int>>permute(vector<int>&...
class Solution {public: void sortColors(vector<int>& nums) { int r = 0, g = 0, b = 0; for (int n : nums) { if (n == 0) { nums[b++] = 2; nums[g++] = 1; nums[r++] = 0; } else if (n == 1) { nums[b++] = 2; nums[g++] =...
class Solution { public: vector<int> advantageCount(vector<int> &nums1, vector<int> &nums2) { int n = nums1.size(), ids[n]; vector<int> ans(n); sort(nums1.begin(), nums1.end()); iota(ids, ids + n, 0); // 给定 地址范围,和 初值,给这个范围赋值,步长为1 //sort(起始地址...
class Solution: def maxSubArray(self, nums: List[int]) -> int: return self.helper(nums, 0, len(nums) - 1) def helper(self, nums, l, r): if l > r: return -sys.maxsize mid = (l + r) // 2 left = self.helper(nums, l, mid - 1...
classSolution {public:intremoveDuplicates(vector<int>&nums) {intlength =nums.size();if(length ==0)return0;intflag =0;for(inti =1; i < length; i++){while(nums[i] ==nums[flag]){if(i < length-1) i++;elsebreak; }flag++;
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: hashtable = dict() for i, num in enumerate(nums): if target - num in hashtable: return [hashtable[target - num], i] hashtable[nums[i]] = i ...
这里是python代码实现:pythonclass Solution: def maximizeSum(self, nums: List[int], k: int) -> int: m = max(nums) return (2*m + k - 1) * k // 2解答思路:1. 首先找到数组中的最大值m。2. 然后最大的得分公式为:m + (m+1) + (m+2) + ... + (m+k-1) = (m...
2、无脑递归法classSolution{ public: intnumberOfMatches(intn){ if( n ==1)return0; returnn/2+ numberOfMatches((n+1)/2); } }; 3、不讲武德法 冠军只有一个,意味着n - 1个队伍需要淘汰,而每场比赛只能淘汰一个队伍,换言之需要淘汰n - 1个队伍需要比赛n - 1次,所以,答案出来了,一行代码 AC...