diff --git a/company/adobe/AddDigits.java b/company/adobe/AddDigits.java index a2d7b727..0dd86d6e 100644 --- a/company/adobe/AddDigits.java +++ b/company/adobe/AddDigits.java @@ -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; } } diff --git a/company/adobe/MajorityElement.java b/company/adobe/MajorityElement.java index 4fbb79b6..92b5d0a4 100644 --- a/company/adobe/MajorityElement.java +++ b/company/adobe/MajorityElement.java @@ -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 map = new HashMap(); + // 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 map = new HashMap(); - 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; } }