koenjazh-CNfresde
짬뽕얼큰하게의 맨땅에 헤딩 :: Special Array I

Special Array I

알고리즘 2025. 2. 2. 10:28

summary

  • Check if an array is special, where every pair of adjacent elements contains two numbers with different parity.

approach

  • Use a flag variable to track the parity of the first element
  • Then, iterate through the array, updating the flag variable based on the parity of each element
  • If a pair of adjacent elements has the same parity, return false
  • Otherwise, return true if all pairs have different parity.

complexity

  • O(n), where n is the number of elements in the array

explain

  • The solution uses bitwise operations to check the parity of each element
  • The expression `nums[i] & 1` checks if the least significant bit of `nums[i]` is 1 (i.e., the number is odd)
  • The `flag ^ (nums[i] & 1)` expression updates the flag variable based on the parity of `nums[i]`
  • If `flag` and `nums[i]` have different parity, `flag` is set to the opposite parity
  • If they have the same parity, `flag` remains unchanged
  • The solution returns false as soon as it encounters a pair of adjacent elements with the same parity, and returns true otherwise.

Solution Code:


class Solution {
public:
    bool isArraySpecial(vector& nums) {
        bool flag = nums[0] & 1;
        for(int i = 1; i < nums.size(); i++){
            if(flag ^ (nums[i] & 1)){
                flag ^= 1;
            } else{
                return false;
            }
        }
        return true;
    }
};

'알고리즘' 카테고리의 다른 글

Find Center of Star Graph  (0) 2025.02.02
Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit  (0) 2025.02.02
Check if Array Is Sorted and Rotated  (0) 2025.02.02
Making A Large Island  (0) 2025.02.02
Redundant Connection  (0) 2025.02.01
블로그 이미지

짬뽕얼큰하게

,