11.29 First record
Leetcode 941
Effective mountains
- Question requirement: Given an integer array A, if it is a valid mountain array, return true, otherwise return false.
- If A satisfies the following conditions, then it is an array of mountains:
- A.length >= 3
- Under the condition of 0 <i <A.length-1, there is i such that:
- A[0] < A[1] < … A[i-1] < A[i]
- A[i] > A[i+1] > … > A[A.length - 1]
My code
public boolean validMountainArray(int[] arr) {
int N = arr.length;
int i=0;
while(i+1<N && arr[i]<arr[i+1]){
i++;
}
if(i==0 || i==N-1){
return false;
}
else{
while(arr[i]>arr[i+1])
i++;
if(i == N-1) return true;
else return false;
}
}
Leetcode 349
Intersection of two arrays
- Given two arrays, write a function to calculate their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4 ,9,8,4] Output: [9,4]
Note:
Each element in the output result must be unique.
We can ignore the order of output results.
Reference Code
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<Integer>();
Set<Integer> set2 = new HashSet<Integer>();
for (int num : nums1) {
set1.add(num);
}
for (int num : nums2) {
set2.add(num);
}
return getIntersection(set1, set2);
}
public int[] getIntersection(Set<Integer> set1, Set<Integer> set2) {
if (set1.size() > set2.size()) {
return getIntersection(set2, set1);
}
Set<Integer> intersectionSet = new HashSet<Integer>();
for (int num : set1) {
if (set2.contains(num)) {
intersectionSet.add(num);
}
}
int[] intersection = new int[intersectionSet.size()];
int index = 0;
for (int num : intersectionSet) {
intersection[index++] = num;
}
return intersection;
}
My code (imitation, still collection method)
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
return new int[0];
}
Set<Integer> parentSet = new HashSet<>();
Set<Integer> childSet = new HashSet<>();
for (int num : nums1) {
parentSet.add(num);
}
for (int num : nums2) {
if (parentSet.contains(num)) {
childSet.add(num);
}
}
int[] resArr = new int[childSet.size()];
int index = 0;
for (int value : childSet) {
resArr[index++] = value;
}
return resArr;
}