June 07, 2020

Find the odd one from a non empty integer array in java

Given a non-empty array of integers, every element appears twice except for one. Find that single one.

class Cfed{

public int singleNumber(int[] nums) {
int length = nums.length;
for (int i = 0; i < length - 1; i++) {
if (nums[i] > nums[i + 1]) {
int temp = nums[i];
nums[i] = nums[i + 1];
nums[i + 1] = temp;
i = -1;
}
}
int i = 0;
int ans = nums[length-1];
while (i+1 < length) {
if(nums[i]!=nums[i+1]) {
ans =  nums[i];
break;
}
i+=2;
}
return ans;
}

public static void main(String[] args) {
Cfed s = new Cfed();
int[] nums = { 4,1,2,1,2 }; 
System.out.println(s.singleNumber(nums));
}
}

No comments:

Post a Comment

Your feedback may help others !!!

Facebook comments