Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save SuryaPratapK/246f773c96a2afcf5c634c57384781a9 to your computer and use it in GitHub Desktop.
Save SuryaPratapK/246f773c96a2afcf5c634c57384781a9 to your computer and use it in GitHub Desktop.
class Solution {
public:
vector<int> applyOperations(vector<int>& nums) {
//Apply operations and maintain non-zero operations on the left side
int n=nums.size();
int non_zero_idx=0;
for(int i=0;i<n;++i){
if(i<n-1 and nums[i]==nums[i+1]){
nums[i]*=2;
nums[i+1]=0;
}
if(nums[i]!=0)
swap(nums[i],nums[non_zero_idx++]);
}
return nums;
}
};
/*
//JAVA
import java.util.Arrays;
class Solution {
public int[] applyOperations(int[] nums) {
int n = nums.length;
int nonZeroIdx = 0;
// Apply operations
for (int i = 0; i < n; ++i) {
if (i < n - 1 && nums[i] == nums[i + 1]) {
nums[i] *= 2;
nums[i + 1] = 0;
}
if (nums[i] != 0) {
int temp = nums[i];
nums[i] = nums[nonZeroIdx];
nums[nonZeroIdx] = temp;
nonZeroIdx++;
}
}
return nums;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] nums = {1, 2, 2, 0, 3, 0, 4};
int[] result = sol.applyOperations(nums);
System.out.println(Arrays.toString(result)); // Output: [1, 4, 3, 4, 0, 0, 0]
}
}
#Python
from typing import List
class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
n = len(nums)
non_zero_idx = 0
# Apply operations
for i in range(n):
if i < n - 1 and nums[i] == nums[i + 1]:
nums[i] *= 2
nums[i + 1] = 0
if nums[i] != 0:
nums[i], nums[non_zero_idx] = nums[non_zero_idx], nums[i]
non_zero_idx += 1
return nums
# Example usage
sol = Solution()
nums = [1, 2, 2, 0, 3, 0, 4]
result = sol.applyOperations(nums)
print(result) # Output: [1, 4, 3, 4, 0, 0, 0]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment