In a standard HashMap implementation, each key must be unique. If you attempt to put the same key with a different value into a HashMap, the new value will overwrite the existing value associated with that key. This is because the purpose of a HashMap is to provide a one-to-one mapping between keys and values.
pros/cons
Advantages of Hash:
Hash provides better synchronization than other data structures.
Hash tables are more efficient than search trees or other data structures.
Hash provides constant time for searching, insertion and deletion operations on average.
Hash tables are space-efficient.
Most Hash table implementation can automatically resize itself.
Hash tables are easy to use.
Hash tables offer a high-speed data retrieval and manipulation.
Disadvantages of Hash:
Hash is inefficient when there are many collisions.
Hash collisions are practically not be avoided for large set of possible keys.
Hash does not allow null values.
Hash tables have a limited capacity and will eventually fill up.
Hash tables can be complex to implement.
Hash tables do not maintain the order of elements, which makes it difficult to retrieve elements in a specific order.
// Import the HashSet class import java.util.HashSet;
publicclassMain { publicstaticvoidmain(String[] args) { HashSet<String> cars = newHashSet<String>(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("BMW"); cars.add("Mazda"); System.out.println(cars); cars.contains("Mazda"); cars.remove("Volvo"); //To remove all items, use the clear() method: cars.clear(); cars.size(); //Loop through the items of an HashSet with a for-each loop: for (String i : cars) { System.out.println(i); } } }
ArrayList:
a resizable array
ArrayList allows duplicate values in its collection. On other hand duplicate elements are not allowed in Hashset.
publicclassMain { publicstaticvoidmain(String[] args) { ArrayList<String> cars = newArrayList<String>(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); for (inti=0; i < cars.size(); i++) { System.out.println(cars.get(i)); } for (inti=0; i < cars.size(); i++) { System.out.println(cars.get(i)); } } } //To modify an element, use the set() method and refer to the index number: cars.set(0, "Opel"); //To remove an element, use the remove() method and refer to the index number: cars.remove(0); //To remove all the elements in the ArrayList, use the clear() method: cars.clear(); //To find out how many elements an ArrayList have, use the size method: cars.size();
classSolution { public List<String> commonChars(String[] words) { intnumb= words.length; List<String> result = newArrayList<>(); if(words.length == 0) return result; int[] dict = newint[26]; // first string in the array for(inti=0; i < words[0].length(); i++){ dict[words[0].charAt(i) - 'a']++; } for(inti=1;i < words.length; i++){ int[] temp = newint[26]; for(intj=0; j < words[i].length(); j++){ temp[words[i].charAt(j) - 'a']++; } //compare ith string to the first string, take the min for(intk=0; k < 26; k++){ dict[k]=Math.min(dict[k],temp[k]); } } for(intx=0; x < 26; x++){ while(dict[x] != 0){ // notice, here we should use while not if charres= (char)(x + 'a'); Stringre= Character.toString(res); result.add(re); dict[x] --; } } return result; } }
classSolution { publicint[] intersection(int[] nums1, int[] nums2) { HashMap<Integer, Integer> dict = newHashMap<>(); HashSet<Integer> ans = newHashSet<Integer>(); // use HashSet cause we don't want repetitive number for(int i : nums1){ dict.put(i , dict.getOrDefault(i ,0) + 1); } for(int j : nums2){ if(dict.getOrDefault(j,0) > 0){ ans.add(j); dict.put(j , dict.getOrDefault(j, 0) - 1); } } // convert hashset into int array int[] num = newint[ans.size()]; intindex=0; for(Integer i : ans){ // you can write --> int i : ans , it is also right num[index++] = i; } return num; } }
class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> map = new HashMap<>(); for(int i = 0; i < nums.length; i++){ map.put(nums[i], i); }
for(int i = 0; i < nums.length; i++){ int addNum = target - nums[i]; if(map.containsKey(addNum)){ int[] res = {i, map.get(addNum)}; return res; } } return new int[]{}; } }
Here’s an example to illustrate the problem:
Input:
1 2
makefileCopy codenums = [3, 2, 4, 4] target = 8
With your current code, it would return [2, 2] because the number 4 appears twice in the array, and the HashMap will only store one of the occurrences.
其实在本题的情况下,使用map的空间消耗要比数组大一些的,因为map要维护红黑树或者哈希表,而且还要做哈希函数,是费时的!数据量大的话就能体现出来差别了。 所以数组更加简单直接有效!if you want to record the number that a certain letter appears in a string you can actually just use Array instead of HashMap, it’s simpler and save more space.
for(char c : ransomNote.toCharArray()){ record[c - 'a'] -= 1; } // 如果数组中存在负数,说明ransomNote字符串总存在magazine中没有的字符 for(int i : record){ if(i < 0){ returnfalse; // can check if there's negative in the last loop. two loops are enough to solve this question. } }
Notice that the solution set must not contain duplicate triplets.
Example :
1 2 3 4 5 6 7 8
Input: nums = [-1,0,1,2,-1,-4] Output: [[-1,-1,2],[-1,0,1]] Explanation: nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1,0,1] and [-1,-1,2]. Notice that the order of the output and the order of the triplets does not matter.
classSolution { public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> result = newArrayList<>(); Arrays.sort(nums); // 找出a + b + c = 0 // a = nums[i], b = nums[left], c = nums[right] for (inti=0; i < nums.length; i++) { // 排序之后如果第一个元素已经大于零,那么无论如何组合都不可能凑成三元组,直接返回结果就可以了 if (nums[i] > 0) { return result; }
if (i > 0 && nums[i] == nums[i - 1]) { // 去重a //notice这里只能是 i - 1不能是 i + 1, 因为如果是i + 1的话,判断的是结果集里面有没有重复的元素eg:{-1,-1,2} continue; } /* you can also write like this while (i > 0 && i < nums.length && nums[i] == nums[i - 1]) { // 去重a i++; } */ intleft= i + 1; intright= nums.length - 1; while (right > left) { intsum= nums[i] + nums[left] + nums[right]; if (sum > 0) { right--; } elseif (sum < 0) { left++; } else { result.add(Arrays.asList(nums[i], nums[left], nums[right])); //!!! // 去重逻辑应该放在找到一个三元组之后,对b 和 c去重 while (right > left && nums[right] == nums[right - 1]) right--; while (right > left && nums[left] == nums[left + 1]) left++; right--; //!!!!!!! left++; //!!!!!!!! } } } return result; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14
while(left < right){ if(nums[i] + nums[left] + nums[right] > 0) right--; if(nums[i] + nums[left] + nums[right] < 0) left ++; if(nums[i] + nums[left] + nums[right] == 0){ res.add(Arrays.asList(nums[i], nums[left], nums[right])); while(right > left && nums[left] == nums[left + 1]) left++; while(right > left && nums[right] == nums[right - 1] ) right--; left++; right--; } } } //!!!!!!!!!!! here use three if's -> it's wrong //!!!!!!!!!!!!should use if, else if, else
In Java, Arrays.asList is a method that is used to convert an array into a fixed-size list.
public class ArrayToListExample { public static void main(String[] args) { // Create an array String[] array = {"Java", "is", "awesome"};
// Convert the array to a list List<String> list = Arrays.asList(array);
// Now you can work with the list System.out.println("List elements: " + list);
// Note that this list is backed by the original array, so changes to the list // will affect the array, and vice versa list.set(1, "rocks"); System.out.println("Updated list: " + list); System.out.println("Original array: " + Arrays.toString(array)); } }
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
1 2 3 4 5 6 7 8
Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000
For example, 2 is written as II in Roman numeral, just two one’s added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
classSolution { publicintlongestConsecutive(int[] nums) { HashMap<Integer, Integer> map = newHashMap<>(); intres=0 ; for(inti=0; i < nums.length; i++){ if(!map.containsKey(nums[i])){ intleft= map.getOrDefault(nums[i] - 1, 0); intright= map.getOrDefault(nums[i] + 1, 0); intsum= left + right + 1; //renew the map inf map.put(nums[i], sum); map.put(nums[i] - left, sum);// notice here you should substract left not substract 1. cause there might be more than one consecutive numbers. map.put(nums[i] + right, sum);
The DNA sequence is composed of a series of nucleotides abbreviated as 'A', 'C', 'G', and 'T'.
For example, "ACGAATTCCG" is a DNA sequence.
When studying DNA, it is useful to identify repeated sequences within the DNA.
Given a string s that represents a DNA sequence, return all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in any order.
Example 1:
1 2
Input: s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" Output: ["AAAAACCCCC","CCCCCAAAAA"]
class Solution { public List<String> findRepeatedDnaSequences(String s) { HashSet<String> map = new HashSet<>(); HashSet<String> ress = new HashSet<>(); // to get rid of duplicates for(int i = 0; i < s.length() - 9; i++){ //!!!! -9 not - 10 //think about s.length = 11, it should loop twice StringBuilder sb = new StringBuilder(); for(int j = i; j < i+10; j++){ sb.append(s.charAt(j)); } String dna = sb.toString(); if(map.contains(dna)){ ress.add(dna); }else{ map.add(dna); } } return new ArrayList<>(ress); //!!!! }
improve:
class Solution { public List<String> findRepeatedDnaSequences(String s) { HashSet<String> map = new HashSet<>(); HashSet<String> res = new HashSet<>(); for(int i = 0; i < s.length() - 9; i++){ String dna = s.substring(i, i+10); //!!!! not subString if(map.contains(dna)){ res.add(dna); }else{ map.add(dna); } }
You are playing the Bulls and Cows game with your friend.
You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info:
The number of “bulls”, which are digits in the guess that are in the correct position.
The number of “cows”, which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.
Given the secret number secret and your friend’s guess guess, return the hint for your friend’s guess.
The hint should be formatted as "xAyB", where x is the number of bulls and y is the number of cows. Note that both secret and guess may contain duplicate digits.
Example 1:
1 2 3 4 5 6
Input: secret = "1807", guess = "7810" Output: "1A3B" Explanation: Bulls are connected with a '|' and cows are underlined: "1807" | "7810"
Example 2:
1 2 3 4 5 6 7
Input: secret = "1123", guess = "0111" Output: "1A1B" Explanation: Bulls are connected with a '|' and cows are underlined: "1123" "1123" | or | "0111" "0111" Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull.
There is a forest with an unknown number of rabbits. We asked n rabbits “How many rabbits have the same color as you?” and collected the answers in an integer array answers where answers[i] is the answer of the ith rabbit.
Given the array answers, return the minimum number of rabbits that could be in the forest.
Example 1:
1 2 3 4 5 6 7 8
Input: answers = [1,1,2] Output: 5 Explanation: The two rabbits that answered "1" could both be the same color, say red. The rabbit that answered "2" can't be red or the answers would be inconsistent. Say the rabbit that answered "2" was blue. Then there should be 2 other blue rabbits in the forest that didn't answer into the array. The smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't.
class Solution { public int numRabbits(int[] answers) { HashMap<Integer,Integer> map = new HashMap<>(); int res = 0; for(int i = 0 ; i < answers.length; i++){ if(answers[i] == 0) res+= 1; else if(!map.containsKey(answers[i])){ res += answers[i] + 1; map.put(answers[i],1); } else{ if(map.get(answers[i])>= 1 + answers[i]){ //notice here is >= not > // this if statement is very important res += answers[i] + 1; map.put(answers[i],1); }else{ map.put(answers[i],map.get(answers[i])+1); } } } return res; } }
1.this question is simple but hard to think about the situation like [0,0,1,1,1]
use if elseif else, it easy to get in trouble to use if if if sometimes: