今天也要开始在leetcode刷算法题了,第一天先来点简单的练练手。下面的思路都很好理解,至于更好的写法可以参考leetcode官网给出的解题思路。
同时我会在题目前标好题号,方便日后查找。
(1)两数之和
实现
简单的暴力实现。
class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i = 0; i<nums.length;i++){
for(int j = i + 1; j < nums.length; j++){
if(nums[i] + nums[j] == target){
return new int[]{i,j};
}
}
}
return new int[]{};
}
}
(面试题02.01)移除重复节点
编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。
实现
class Solution {
public ListNode removeDuplicateNodes(ListNode head) {
if(head == null){
return head;
}
ListNode i = head;
ListNode j = head.next;
Set<Integer> set = new HashSet<Integer>();
set.add(i.val);
while(j != null){
if(set.add(j.val) == false){
// 直接跨过i
i.next = j.next;
j = j.next;
}else{
i = j;
j = j.next;
}
}
return head;
}
}
(938)二叉搜索树的范围和
实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
//深度优先
public int rangeSumBST1(TreeNode root, int low, int high) {
if(root == null){
return 0;
}
if(root.val < low){
return rangeSumBST(root.right,low,high);
}
if(root.val > high){
return rangeSumBST(root.left,low,high);
}
return rangeSumBST(root.left,low,high) + rangeSumBST(root.right,low,high) + root.val;
}
// 广度优先
public int rangeSumBST(TreeNode root, int low, int high){
int sum = 0;
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.offer(root);
while(!q.isEmpty()){
TreeNode node = q.poll();
if(node == null){
continue;
}
if(node.val > high){
q.offer(node.left);
}else if(node.val < low){
q.offer(node.right);
}else{
sum += node.val;
q.offer(node.left);
q.offer(node.right);
}
}
return sum;
}
}