Leetcode 2903. Find Indices With Index and Value Difference I
You are given an integer array nums. You need to return all indices i such that i is equal to nums[i]. Return the list of indices in ascending order.
nums?
The problem requires us to identify all indices i such that the value at nums[i] is equal to i. This problem can be solved using a straightforward linear scan of the array.
Steps:
i, if nums[i] equals i, add i to the result list.#include <vector>
#include <iostream>
std::vector<int> findIndicesWithIndexAndValueDifference(std::vector<int>& nums) {
std::vector<int> result;
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] == i) {
result.push_back(i);
}
}
return result;
}
int main() {
// Test case
std::vector<int> nums = {0, 2, 2, 3, 4};
std::vector<int> result = findIndicesWithIndexAndValueDifference(nums);
std::cout << "Indices: ";
for (int index : result) {
std::cout << index << " ";
}
return 0;
}
n is the number of elements in the input array nums. This is because we are traversing the array once to check the condition for each element.k is the number of indices that satisfy the condition nums[i] == i.The above solution is efficient and straightforward, leveraging a single pass through the array to achieve the desired result.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?