349. Intersection of Two Arrays
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Note:
Each element in the result must be unique.
The result can be in any order.
给出两个数组,写一个功能来计算他们的交集
注意:在结果中每一个元素都是独一无二的,结果中的元素可以是任意顺序
package com.leetcode.array;
import java.util.*;
public class Intersection_of_Two_Arrays {
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1.length == 0 || nums2.length == 0)
return new int[0];
Set<Integer> set_1 = new HashSet<>();
for (int num : nums1)
set_1.add(num);
Set<Integer> set_2 = new HashSet<>();
for (int num : nums2)
if (set_1.contains(num))
set_2.add(num);
int[] result = new int[set_2.size()];
int i = 0;
for (Integer num : set_2)
result[i++] = num;
return result;
}
public static void main(String[] args) {
int[] nums1 = {1, 2, 2, 1};
int[] nums2 = {2, 2};
int[] result = (new Intersection_of_Two_Arrays()).intersection(nums1, nums2);
for (Integer num : result) {
System.out.print(num + " ");
}
}
}
350. Intersection of Two Arrays II
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?
给出两个数组,计算他们的交集。
注意:每个元素的出现次数应该和他们在数组中出现次数相同。结果可以是任意顺序的。
package com.leetcode.array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Intersection_of_Two_Arrays_II {
public int[] intersect(int[] nums1, int[] nums2) {
if (nums1.length == 0 || nums2.length == 0)
return new int[0];
Map<Integer, Integer> map_1 = new HashMap<>();
for (int num : nums1)
map_1.put(num, map_1.getOrDefault(num, 0) + 1);
List<Integer> list = new ArrayList<>();
for (int num : nums2) {
if (map_1.containsKey(num)){
if (map_1.get(num) <= 0)
continue;
list.add(num);
map_1.put(num, map_1.get(num)-1);
}
}
int[] result = new int[list.size()];
int i = 0;
for (Integer num:list)
result[i++] = num;
return result;
}
public static void main(String[] args) {
int[] nums1 = {1, 2, 2, 1, 3, 3, 4, 3, 2, 4, 2, 5, 3, 2, 1, 3, 2, 1, 2, 0};
int[] nums2 = {2, 2, 3, 1, 32, 21, 1, 1, 1, 1, 3, 12};
int[] result = (new Intersection_of_Two_Arrays_II()).intersect(nums1, nums2);
for (int num : result)
System.out.print(num + " ");
}
}
242. Valid Anagram
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
Note:
You may assume the string contains only lowercase alphabets.
Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?
给出两个字符串s 和t,判断 t 是否是s 的一个字谜。(字谜指t与s中的字母出现次数相同,但出现顺序可能不同)
注意:你应该假定字符串只包含小写字母
package com.leetcode.String;
import java.util.HashMap;
import java.util.Map;
public class Valid_Anagram {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length())
return false;
if (s.length() == 0 && t.length() == 0)
return true;
Map<Character, Integer> map_1 = new HashMap<>();
for (int i = 0; i < s.length(); i++)
map_1.put(s.charAt(i), map_1.getOrDefault(s.charAt(i), 0) + 1);
for (int i = 0; i < t.length(); i++)
if (map_1.containsKey(t.charAt(i)))
map_1.put(t.charAt(i), map_1.get(t.charAt(i)) - 1);
else
return false;
for (Integer count : map_1.values())
if (count != 0)
return false;
return true;
}
public static void main(String[] args) {
String s = "";
String t = "";
boolean result = (new Valid_Anagram()).isAnagram(s, t);
System.out.print(result + " ");
}
}
202. Happy Number
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example: 19 is a happy number
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
思路:当某个结果出现不止一次时,将陷入无限的循环
package com.leetcode.number;
import java.util.HashSet;
import java.util.Set;
public class Happy_Number {
public boolean isHappy(int n) {
Set<Integer> set = new HashSet<>();
int result = countSquare(n);
while (true) {
if (result == 1)
return true;
if (set.contains(result))
return false;
else
set.add(result);
result = countSquare(result);
}
}
public int countSquare(int n) {
int result = 0;
while (n != 0) {
int temp = n % 10;
n /= 10;
result += temp*temp;
}
return result;
}
public static void main(String[] args) {
int n = 19;
System.out.print((new Happy_Number()).isHappy(n));
}
}
290. Word Pattern
Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.
Examples:
pattern = "abba", str = "dog cat cat dog" should return true.
pattern = "abba", str = "dog cat cat fish" should return false.
pattern = "aaaa", str = "dog cat cat dog" should return false.
pattern = "abba", str = "dog dog dog dog" should return false.
Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.
思路,将pattern 中的 char 和 str 中的单词分别作为 key 和 value 放入 map 中,若相同的 key 对应不同的 value 或是相同的 value 对应不同的 kay ,则返回 false
package com.leetcode.String;
import java.util.HashMap;
import java.util.Map;
public class Word_Pattern {
public boolean wordPattern(String pattern, String str) {
String[] str_arr = str.split(" ");
if (pattern.length() != str_arr.length)
return false;
Map<Character, String> map = new HashMap<>();
for (int i = 0; i < pattern.length(); i++) {
if (map.containsKey(pattern.charAt(i)))
if (!map.get(pattern.charAt(i)).equals(str_arr[i]))
return false;
if (!map.containsKey(pattern.charAt(i)))
if (map.containsValue(str_arr[i]))
return false;
map.put(pattern.charAt(i), str_arr[i]);
}
return true;
}
public static void main(String[] args) {
String str = "dog dog dog dog";
String pattern = "abba";
System.out.print((new Word_Pattern()).wordPattern(pattern, str));
}
}
205. Isomorphic Strings
Given two strings s and t, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.
For example,
Given "egg", "add", return true.
Given "foo", "bar", return false.
Given "paper", "title", return true.
Note:
You may assume both s and t have the same length.
与上一题思路相似
package com.leetcode.String;
import java.util.HashMap;
import java.util.Map;
public class Isomorphic_Strings {
public boolean isIsomorphic(String s, String t) {
if (s.length() != t.length())
return false;
Map<Character, Character> map = new HashMap<>();
for (int i = 0; i < s.length(); i++){
if (!map.containsKey(s.charAt(i))){
if (map.containsValue(t.charAt(i)))
return false;
map.put(s.charAt(i), t.charAt(i));
}else {
if (!map.get(s.charAt(i)).equals(t.charAt(i)))
return false;
}
}
return true;
}
public static void main(String[] args){
String s = "foo";
String t = "bar";
System.out.print((new Isomorphic_Strings()).isIsomorphic(s, t));
}
}
451. Sort Characters By Frequency
Given a string, sort it in decreasing order based on the frequency of characters.
Input:
"tree"
Output:
"eert"
Explanation:
'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
思路,使用 map 统计字符的出现次数,使用 桶排序的思想进行排序
package com.leetcode.String;
import java.util.*;
public class Sort_Characters_By_Frequency {
public String frequencySort(String s) {
char[] ch_arr = s.toCharArray();
Map<Character, Integer> map = new HashMap<>();
for (char ch : ch_arr) {
map.put(ch, map.getOrDefault(ch, 0) + 1);
}
List<Character>[] bucket = new List[s.length() + 1];
for (Character ch : map.keySet()) {
int count = map.get(ch);
if (bucket[count] == null) {
bucket[count] = new ArrayList<>();
}
bucket[count].add(ch);
}
StringBuilder stringBuilder = new StringBuilder();
for (int i = bucket.length - 1; i >= 0; i--) {
if (bucket[i] != null) {
int count;
int list_size = bucket[i].size();
while (list_size != 0) {
count = i;
while (count != 0) {
stringBuilder.append(bucket[i].get(list_size - 1));
count--;
}
list_size--;
}
}
}
return stringBuilder.toString();
}
public static void main(String[] args) {
String s = "Aabb";
System.out.print((new Sort_Characters_By_Frequency()).frequencySort(s));
}
}
347. Top K Frequent Elements
Given a non-empty array of integers, return the k most frequent elements.
For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].
Note:
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
package com.leetcode.array;
import java.util.*;
public class Top_K_Frequent_Elements {
public List<Integer> topKFrequent(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
Set<Integer>[] bucket = new HashSet[nums.length + 1];
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (bucket[entry.getValue()] == null) {
bucket[entry.getValue()] = new HashSet<>();
}
bucket[entry.getValue()].add(entry.getKey());
}
List<Integer> result = new ArrayList<>();
int count = 0;
for (int i = bucket.length - 1; i >= 0; i--) {
if (bucket[i] != null) {
for (Integer num: bucket[i]){
if (count >= k)
break;
result.add(num);
count++;
}
}
}
return result;
}
public static void main(String[] args) {
int[] arr = {4, 1, -1, 2, -1, 2, 3};
int k = 2;
List<Integer> result = (new Top_K_Frequent_Elements()).topKFrequent(arr, k);
for (Integer num : result)
System.out.print(num + " ");
}
}
作者:HeatDeath 发表于2017/11/26 16:00:53
原文链接