169. Majority Element
The Title requirements are as follows
Given an array of size n, find the majority element. The majority
element is the element that appears more than ⌊ n/2 ⌋ times.You may assume that the array is non-empty and the majority element
always exist in the array.
The solution to the problem is as follows, using HashMap
import java.util.*;
public class Solution {
public int majorityElement(int[] nums) {
Map<Integer,Integer>m=new HashMap<>();
for(int i=0;i<nums.length;i++){
if(!m.containsKey(nums[i])){
m.put(nums[i],1);
}
else{
m.put(nums[i],m.get(nums[i])+1);
}
if(m.get(nums[i])>nums.length/2) return nums[i];
}
return 0;
}
}
350. Intersection of Two Arrays II
The Title requirements are as follows
Given two arrays, write a function to compute their intersection.
Example: Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Note: Each element in the result should appear as many times as it
shows in both arrays. The result can be in any order.Follow up:
What if the given array is already sorted? How would you optimize your algorithm?
What if nums1's size is small compared to nums2's size?
Which algorithm is better? What if elements of nums2 are stored on
disk, and the memory is limited such that you cannot load all elements into the memory at once?
The solution to the problem is as follows.
public class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
ArrayList<Integer> result = new ArrayList<Integer>();
for(int i = 0; i < nums1.length; i++)
{
if(map.containsKey(nums1[i])) map.put(nums1[i], map.get(nums1[i])+1);
else map.put(nums1[i], 1);
}
for(int i = 0; i < nums2.length; i++)
{
if(map.containsKey(nums2[i]) && map.get(nums2[i]) > 0)
{
result.add(nums2[i]);
map.put(nums2[i], map.get(nums2[i])-1);
}
}
int[] r = new int[result.size()];
for(int i = 0; i < result.size(); i++)
{
r[i] = result.get(i);
}
return r;
}
}
HashMap is used to solve both problems. HashMap can efficiently access key-value pairs.
HashMap is based on hashing principle. We store and obtain objects by put() and get(). When we pass the key-value pair to the put() method, it calls the hashCode() method of the key object to calculate the hashcode so that the bucket location can be found to store the value object. When the object is acquired, the correct key-value pair is found by the equals() method of the key object, and then the value object is returned. HashMap uses linked lists to solve collision problems. When collisions occur, objects are stored in the next node of the linked list. HashMap stores key-value pairs in each linked list node.
What happens when two different key objects have the same hashcode? They are stored in a linked list at the same bucket location. The equals() method of the key object is used to find key-value pairs.
Reference: Link to the original text: Javarevisited
Translation: Importnew-Tang Xiao Juan
Translation Links: http://www.importnew.com/7099.html