LeetCode 3936: Find X Value of Array XVI (Greedy Simulation)
LeetCode 3936Source: https://leetcode.com/problems/find-x-value-of-array-xvi/
English
Scan the array from left to right and keep the current candidate x. At each step, apply the operation rule between x and nums[i], then update x greedily. The key is that each update is local and irreversible, so one linear pass gives the final value.
Complexity: O(n) time, O(1) extra space.
class Solution {
public int findXValue(int[] nums) {
int x = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] > x) x = nums[i] - x;
else x -= nums[i];
}
return x;
}
}func findXValue(nums []int) int {
x := nums[0]
for i := 1; i < len(nums); i++ {
if nums[i] > x { x = nums[i] - x } else { x -= nums[i] }
}
return x
}class Solution {
public:
int findXValue(vector<int>& nums) {
int x = nums[0];
for (int i = 1; i < (int)nums.size(); ++i) {
if (nums[i] > x) x = nums[i] - x;
else x -= nums[i];
}
return x;
}
};class Solution:
def findXValue(self, nums: list[int]) -> int:
x = nums[0]
for i in range(1, len(nums)):
x = nums[i] - x if nums[i] > x else x - nums[i]
return xfunction findXValue(nums) {
let x = nums[0];
for (let i = 1; i < nums.length; i++) {
x = nums[i] > x ? nums[i] - x : x - nums[i];
}
return x;
}中文
从左到右扫描数组,维护当前候选值 x。每遇到一个新元素,就按题目给定规则在 x 和 nums[i] 之间做一次更新。由于每一步只依赖当前状态且不会回退,线性遍历即可得到最终答案。
复杂度:时间 O(n),额外空间 O(1)。
class Solution {
public int findXValue(int[] nums) {
int x = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] > x) x = nums[i] - x;
else x -= nums[i];
}
return x;
}
}func findXValue(nums []int) int {
x := nums[0]
for i := 1; i < len(nums); i++ {
if nums[i] > x { x = nums[i] - x } else { x -= nums[i] }
}
return x
}class Solution {
public:
int findXValue(vector<int>& nums) {
int x = nums[0];
for (int i = 1; i < (int)nums.size(); ++i) {
if (nums[i] > x) x = nums[i] - x;
else x -= nums[i];
}
return x;
}
};class Solution:
def findXValue(self, nums: list[int]) -> int:
x = nums[0]
for i in range(1, len(nums)):
x = nums[i] - x if nums[i] > x else x - nums[i]
return xfunction findXValue(nums) {
let x = nums[0];
for (let i = 1; i < nums.length; i++) {
x = nums[i] > x ? nums[i] - x : x - nums[i];
}
return x;
}
Comments