简单3星
155. 最小栈
看解题
155. 最小栈
class MinStack {
int[] data;
int curLength = 0;
int curMinLength = 0;
int[] minStack;
/**
* initialize your data structure here.
*/
public MinStack() {
data = new int[10];
minStack = new int[10];
}
public int[] grow(int minLength, int[] data) {
int oldLength = data.length;
int newLength = oldLength * 2;
if (minLength > newLength) {
newLength = minLength;
}
// 越界,注意新的长度超过data的长度会越界的
// System.arraycopy(data, 0, data, 0, newLength);
// 返回一个新的数组,如果长度超过原来的长度,则补充0
return Arrays.copyOf(data, newLength);
}
public void push(int x) {
if (curLength + 1 > data.length) {
data = grow(curLength, data);
}
if (curMinLength + 1 > minStack.length) {
minStack = grow(curMinLength, minStack);
}
data[curLength++] = x;
// 必须带=如果不带,会出现重复的数据,在获取最小值时越界
if (curMinLength == 0 || minStack[curMinLength - 1] >= x) {
minStack[curMinLength++] = x;
}
}
public void pop() {
if (data[curLength - 1] == minStack[curMinLength - 1]) {
curMinLength--;
}
curLength--;
}
public int top() {
return data[curLength - 1];
}
public int getMin() {
return minStack[curMinLength - 1];
}
}
226. 翻转二叉树
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
TreeNode right = invertTree(root.right);
TreeNode left = invertTree(root.left);
root.left = right;
root.right = left;
return root;
}
public TreeNode invertTree(TreeNode root) {
if (root == null) return null;
Queue queue = new LinkedList();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode current = queue.poll();
TreeNode temp = current.left;
current.left = current.right;
current.right = temp;
if (current.left != null) queue.add(current.left);
if (current.right != null) queue.add(current.right);
}
return root;
}
234. 回文链表
看解题
69. x 的平方根
class Solution {
public int mySqrt(int x) {
if (x < 2) return x;
long num;
int pivot, left = 2, right = x / 2;
while (left <= right) {
pivot = left + (right - left) / 2;
num = (long)pivot * pivot;
if (num > x) right = pivot - 1;
else if (num < x) left = pivot + 1;
else return pivot;
}
return right;
}
}
415. 字符串相加
class Solution {
public String addStrings(String num1, String num2) {
StringBuilder res = new StringBuilder("");
int i = num1.length() - 1, j = num2.length() - 1, carry = 0;
while(i >= 0 || j >= 0){
int n1 = i >= 0 ? num1.charAt(i) - '0' : 0;
int n2 = j >= 0 ? num2.charAt(j) - '0' : 0;
int tmp = n1 + n2 + carry;
carry = tmp / 10;
res.append(tmp % 10);
i--; j--;
}
if(carry == 1) res.append(1);
return res.reverse().toString();
}
}
83. 删除排序链表中的重复元素
public ListNode deleteDuplicates(ListNode head) {
ListNode current = head;
while (current != null && current.next != null) {
if (current.next.val == current.val) {
current.next = current.next.next;
} else {
current = current.next;
}
}
return head;
}
28. 实现 strStr()
class Solution {
public int strStr(String haystack, String needle) {
int L = needle.length(), n = haystack.length();
if (L == 0) return 0;
int pn = 0;
while (pn < n - L + 1) {
// find the position of the first needle character
// in the haystack string
while (pn < n - L + 1 && haystack.charAt(pn) != needle.charAt(0)) ++pn;
// compute the max match string
int currLen = 0, pL = 0;
while (pL < L && pn < n && haystack.charAt(pn) == needle.charAt(pL)) {
++pn;
++pL;
++currLen;
}
// if the whole needle string is found,
// return its start position
if (currLen == L) return pn - L;
// otherwise, backtrack
pn = pn - currLen + 1;
}
return -1;
}
}
KMP看解题
13. 罗马数字转整数
class Solution {
public int romanToInt(String s) {
Map map = new HashMap<>();
map.put("I", 1);
map.put("IV", 4);
map.put("V", 5);
map.put("IX", 9);
map.put("X", 10);
map.put("XL", 40);
map.put("L", 50);
map.put("XC", 90);
map.put("C", 100);
map.put("CD", 400);
map.put("D", 500);
map.put("CM", 900);
map.put("M", 1000);
int ans = 0;
for(int i = 0;i < s.length();) {
if(i + 1 < s.length() && map.containsKey(s.substring(i, i+2))) {
ans += map.get(s.substring(i, i+2));
i += 2;
} else {
ans += map.get(s.substring(i, i+1));
i ++;
}
}
return ans;
}
}
167. 两数之和 II - 输入有序数组
class Solution {
public int[] twoSum(int[] numbers, int target) {
int low = 0;
int high = numbers.length - 1;
while(low < high){
int sum = numbers[low] + numbers[high];
if(sum == target){
return new int[]{low + 1, high + 1};
}else if(sum > target){
high--;
}else{
low++;
}
}
return new int[]{-1,-1};
}
}
203. 移除链表元素
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode sentinel = new ListNode(0);
sentinel.next = head;
ListNode prev = sentinel, curr = head;
while (curr != null) {
if (curr.val == val) prev.next = curr.next;
else prev = curr;
curr = curr.next;
}
return sentinel.next;
}
}
35. 搜索插入位置
class Solution {
public int searchInsert(int[] nums, int target) {
if(nums.length==0){
return 0;
}
int left = 0;
int right = nums.length;
while(left nums[mid]){
left = mid+1;
}else{
right = mid;
}
}
return right;
}
}
136. 只出现一次的数字
class Solution {
public int singleNumber(int[] nums) {
int a = 0;
for (int i : nums) {
a ^= i;
}
return a;
}
}
108. 将有序数组转换为二叉搜索树
class Solution {
int[] nums;
public TreeNode helper(int left, int right) {
if (left > right) return null;
// always choose left middle node as a root
int p = (left + right) / 2;
// inorder traversal: left -> node -> right
TreeNode root = new TreeNode(nums[p]);
root.left = helper(left, p - 1);
root.right = helper(p + 1, right);
return root;
}
public TreeNode sortedArrayToBST(int[] nums) {
this.nums = nums;
return helper(0, nums.length - 1);
}
}
225. 用队列实现栈
看解题
面试题03. 数组中重复的数字
class Solution {
public int findRepeatNumber(int[] nums) {
Set set = new HashSet();
int repeat = -1;
for (int num : nums) {
if (!set.add(num)) {
repeat = num;
break;
}
}
return repeat;
}
}
118. 杨辉三角
class Solution {
public List> generate(int numRows) {
List> triangle = new ArrayList>();
// First base case; if user requests zero rows, they get zero rows.
if (numRows == 0) {
return triangle;
}
// Second base case; first row is always [1].
triangle.add(new ArrayList<>());
triangle.get(0).add(1);
for (int rowNum = 1; rowNum < numRows; rowNum++) {
List row = new ArrayList<>();
List prevRow = triangle.get(rowNum-1);
// The first row element is always 1.
row.add(1);
// Each triangle element (other than the first and last of each row)
// is equal to the sum of the elements above-and-to-the-left and
// above-and-to-the-right.
for (int j = 1; j < rowNum; j++) {
row.add(prevRow.get(j-1) + prevRow.get(j));
}
// The last row element is always 1.
row.add(1);
triangle.add(row);
}
return triangle;
}
}
38. 外观数列
class Solution {
public String countAndSay(int n) {
String dp= "1" ;
StringBuilder sb = new StringBuilder() ;
for(int i = 1 ; i < n ; i++){
int count = 1 ;
sb = new StringBuilder() ;
char[] ss = dp.toCharArray() ;
int len = ss.length ;
for(int j = 0 ; j < len - 1 ; j++){
if(ss[j] == ss[j+1]){
count++ ;
continue ;
}
sb.append(String.valueOf(count)).append(ss[j]) ;
count = 1 ;
}
sb.append(String.valueOf(count)).append(ss[len-1]) ;
dp = sb.toString() ;
}
return dp ;
}
}
115. 不同的子序列
https://leetcode-cn.com/problems/distinct-subsequences/solution/yi-wei-shu-zu-dpxiang-xi-jie-shi-by-dijks/
面试题62. 圆圈中最后剩下的数字
约瑟夫环
https://leetcode-cn.com/problems/yuan-quan-zhong-zui-hou-sheng-xia-de-shu-zi-lcof/solution/huan-ge-jiao-du-ju-li-jie-jue-yue-se-fu-huan-by-as/
f(N,M)=(f(N−1,M)+M)%n
232. 用栈实现队列
看解题
67. 二进制求和
class Solution {
public String addBinary(String a, String b) {
int ca = 0;
StringBuilder ans = new StringBuilder();
for(int i = a.length()-1,j=b.length()-1;i>=0||j>=0;i--,j--){
int sum = ca + (i>=0 ? a.charAt(i) - '0' : 0) + (j>=0 ? b.charAt(j) - '0' : 0);
ca = sum / 2;
ans.insert(0, sum % 2);
}
if(ca == 1) {
ans.insert(0,1);
}
return ans.toString();
}
}
557. 反转字符串中的单词 III
public class Solution {
public String reverseWords(String s) {
String words[] = split(s);
StringBuilder res=new StringBuilder();
for (String word: words)
res.append(reverse(word) + " ");
return res.toString().trim();
}
public String[] split(String s) {
ArrayList < String > words = new ArrayList < > ();
StringBuilder word = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ') {
words.add(word.toString());
word = new StringBuilder();
} else
word.append( s.charAt(i));
}
words.add(word.toString());
return words.toArray(new String[words.size()]);
}
public String reverse(String s) {
StringBuilder res=new StringBuilder();
for (int i = 0; i < s.length(); i++)
res.insert(0,s.charAt(i));
return res.toString();
}
}
557. 反转字符串中的单词 III
https://leetcode-cn.com/problems/intersection-of-two-arrays/solution/duo-chong-jie-fa-jie-jue-349-liang-ge-shu-zu-de-ji/
66. 加一
class Solution {
public int[] plusOne(int[] digits) {
int length = digits.length;
for(int i = length-1;i>=0 ;i--){
digits[i]++;
digits[i] %=10;
if(digits[i]!=0){
return digits;
}
}
digits = new int[length+1];
digits[0] = 1;
return digits;
}
}