Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

I Changed this java File #224

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 11 additions & 9 deletions company/adobe/AddDigits.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,19 @@
//Could you do it without any loop/recursion in O(1) runtime?

class AddDigits {
public int addDigits(int num) {
while(num >= 10) {
int temp = 0;
while(num > 0) {
temp += num % 10;
num /= 10;
public int addDigits(int n) {
while(n >= 10){
int sum = 0;
while(n > 0){

int digit = n % 10;
sum = sum + digit;
n = n / 10;

}
num = temp;
n = sum;
}

return num;
return n;
}
}

42 changes: 29 additions & 13 deletions company/adobe/MajorityElement.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,38 @@

class MajorityElement {
public int majorityElement(int[] nums) {
if(nums.length == 1) {
return nums[0];
}
// if(nums.length == 1) {
// return nums[0];
// }

// HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
// for(int current: nums) {
// if(map.containsKey(current) && map.get(current) + 1 > nums.length / 2) {
// return current;
// } else if(map.containsKey(current)) {
// map.put(current, map.get(current) + 1);
// } else {
// map.put(current, 1);
// }
// }

HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int current: nums) {
if(map.containsKey(current) && map.get(current) + 1 > nums.length / 2) {
return current;
} else if(map.containsKey(current)) {
map.put(current, map.get(current) + 1);
} else {
map.put(current, 1);
// //no majority element exists
// return -1;
// Here is your Brutofocre solution also
if(nums.length == 1){
return 1;
}
int n = nums.length;
Arrays.sort(nums);
int count = 1;
for(int i = 0; i < nums.length-1; i++){
if(nums[i] == nums[i+1]){
count++;
}
if(count > n/2){
return nums[i];
}
}

//no majority element exists
return -1;
}
}