diff --git a/Arrays101/#169 - Majority Element - Easy/Majority Element - Solution.cpp b/Arrays101/#169 - Majority Element - Easy/Majority Element - Solution.cpp new file mode 100644 index 0000000..33f8407 --- /dev/null +++ b/Arrays101/#169 - Majority Element - Easy/Majority Element - Solution.cpp @@ -0,0 +1,36 @@ +class Solution { + public: + int majorityElement(vector& nums) { + + //Sorting method + + // Hashmap method + unordered_map umap; + for(int x: nums){ + umap[x]++; + } + for(auto i: umap){ + if(i.second >= ((double)nums.size()/2)){ + return i.first; + } + } + return 0; + + // Moore's voting method + int count = 0, candidate = nums[0]; + for(int i=1; i& nums) { + int i = nums.size()-1; + while(i > 0 && nums[i-1] >= nums[i]){ + i--; + } + + if(i==0){ + reverse(nums.begin(), nums.end()); + return; + } + int j = nums.size()-1; + while(j >= i && nums[j] <= nums[i-1]){ + j--; + } + swap(nums[i-1], nums[j]); + reverse(nums.begin()+i, nums.end()); + } + }; \ No newline at end of file diff --git a/Arrays101/#31 - Next Permutation - Medium/Next Permutation.md b/Arrays101/#31 - Next Permutation - Medium/Next Permutation.md new file mode 100644 index 0000000..9999b8c --- /dev/null +++ b/Arrays101/#31 - Next Permutation - Medium/Next Permutation.md @@ -0,0 +1,7 @@ +To solve this question, + +1. We find the first decreasing element from the right calling it the pivot. +2. We check if that element does not exist, which means that the array is sorted in non-ascending order, hence we just return a reversed array. +3. If the element exists, we find the smallest element greater than the pivot element which is to the right of it. +4. We swap the two elements. +5. We reverse the suffix of the pivot element to obtain the answer.