Day #3/50 of Learning DSA
Linear Search, Rotate Array by One, Max Consecutive Ones
Day #3/50 of Learning DSA
Today marks the third day of my journey into learning Data Structures and Algorithms (DSA). I've tackled some intriguing problems that have deepened my understanding of fundamental concepts. I explored the Linear Search algorithm, which involves finding a target element within an array. Additionally, I delved into the problem of rotating an array by one position in a clockwise direction, a task that enhances my grasp of array manipulation. Lastly, I worked on finding the maximum number of consecutive ones in a binary array, a challenge that tests logical thinking and problem-solving skills. Despite having some urgent tasks to attend to, I'm excited to share my progress and insights from today's learning experience.
Linear Seach:
Given an array, nums[] of n integers, and an integer element target, find whether element target is present in the array. Return the index of the first occurrence of target in the array, or -1 if it doesn't exist.
Approach:
Run a loop to search the target element.
Return the
indexof the element if found, else return-1.
int search(vector<int>& nums, int target) {
for(int i=0; i<nums.size(); i++){
if (nums[i] == target) return i;
}
return -1;
}
Rotate Array by One:
Given an array nums, rotate the array by one position in clockwise direction.
Approach:
Store the last element of the array in
tempvariable.Keep shifting the elements from index
itoi-1and lastly update the first elementnums[0]withtemp.
void rotate(vector<int> &nums) {
int n = nums.size();
int temp = nums[n-1];
for (int i=n-1; i>=0; i--){
nums[i] = nums[i-1];
}
nums[0] = temp;
}
Max Consecutive Ones:
Given a binary array nums, return the maximum number of consecutive 1's in the array.
Approach:
Run a loop to traverse the array and increase the counter if occurrence of
1continue.Update the
maxCountif with max ofcount&maxCount, ascountreset if0is encountered.
int findMaxConsecutiveOnes(vector<int>& nums) {
int count = 0;
int maxCount = 0;
for (int val: nums){
if (val == 0){
count = 0;
}
else{
count++;
maxCount = max(count, maxCount);
}
}
return maxCount;
}