LeetCode 1826: Faulty Sensor
Problem Description
Explanation:
Given two arrays sensor1
and sensor2
representing the readings of two sensors, we need to determine if one of the sensors is faulty. The faulty sensor is the one that differs from the other sensor in more than one reading.
To solve this problem, we can iterate through both arrays and compare the readings at each index. If the readings at a particular index are different, we can increment a counter. If the counter exceeds 1, we can conclude that the faulty sensor is the one with the differing readings.
: :
Solutions
class Solution {
public int badSensor(int[] sensor1, int[] sensor2) {
int n = sensor1.length;
int count1 = 0, count2 = 0;
for (int i = 0; i < n; i++) {
if (sensor1[i] != sensor2[i]) {
count1++;
count2++;
}
if (count1 > 1) {
return 1;
}
if (count2 > 1) {
return 2;
}
}
return count1 == 1 ? 1 : 2;
}
}
Loading editor...