Here shows 2 Approaches to slove this problem: Brute Force and Binary Search.
Brute Force
The easiest method is scan the array from left to right. Use two variables to record the index of the first and last element \(\textit{target}\). The time complexity is \(O(n)\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
publicstaticint[] searchRange(int[] nums, int target) { int[] ans = {-1, -1}; intlen= nums.length; for (inti=0; i < len; i++) { if (nums[i] == target && ans[0] == -1) { ans[0] = i; } elseif (nums[i] > target && ans[0] >= 0) { ans[1] = i - 1; return ans; } }
if (ans[0] >= 0) { ans[1] = len - 1; }
return ans; }
Analysis
Time Complexity: \(O(n)\)
Space Complexity: \(O(1)\)
Binary Search
Since the array is sorted in ascending order, so we can binary search to speed up the search.
Considering the start and end positions of target, in fact, what we are looking for is “the first position in the array equal to target” (recorded as \(\textit{leftIdx}\) ) and “the first position greater than The position of target minus one” (recorded as \(\textit{rightIdx}\) ).
In binary search, looking for \(\textit{leftIdx}\) is to find the first index greater than or equal to target in the array, and looking for \(\textit{rightIdx}\) is to find the first index greater than target in the array index of target, then decrement the index by one.
Finally, since \(\textit{target}\) may not exist in the array, we need to re-check the two indices we got \(\textit{leftIdx}\) and \(\textit{rightIdx}\) to see if they meet the conditions, if so It returns \([\textit{leftIdx}, \textit{rightIdx}]\), if it does not match, it returns \([-1, -1]\).
To generate a Pascal’s triangle is as the below animated git shows.PascalTriangleAnimated2.gif
We can find that the Current Layer has only one element more than the Previous Layer. The elements in the Current Layer are equal to the elements in the Previous Layer, which was added one by one after being shifted one bit backward.
Therefore, we only need to deal with the Last Layer. We add a \(0\) at the beginning and the end of the Last Layer. Then sum the corresponding positions to get a New Layer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
public List<List<Integer>> generate(int numRows) { List<List<Integer>> ans = newArrayList<>(); for (inti=0; i < numRows; i++) { List<Integer> oneRow = newArrayList<>(); for (intj=0; j <= i; j++) { if (j == 0 || j == i) { oneRow.add(1); } else { oneRow.add(ans.get(i - 1).get(j - 1) + ans.get(i - 1).get(j)); } }
ans.add(oneRow); }
return ans; }
Analysis
Time Complexity: \(O(n^2)\)
Space Complexity: \(O(1)\)
All suggestions are welcome. If you have any query or suggestion please comment below. Please upvote👍 if you like💗 it. Thank you:-)