Java十大经典排序算法的实现图解
296
2022-08-19
剑指Offer之Java算法习题精讲数组与二叉树
题目一
解法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
http://* 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;
RYBwuHb * }
* }
*/
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return method(nums,0,nums.length-1);
}
public TreeNode method(int[] nums,int lf,int rg){
if(lf>rg){
return null;
}
int mid = lf+(rg-lf)/2;
TreeNode root = new TreeNode(nums[mid]);
root.left = method(nums,lf,mid-1);
root.right = method(nums,mid+1,rg);
return root;
}
}
题目二
解法
class Solution {
public boolean containsDuplicate(int[] nums) {
Hashhttp://Set
for(int i = 0;i if(!set.add(nums[i])){ return true; } set.add(nums[i]); } return false; } } 题目三 解法 class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { Map int length = nums.length; for (int i = 0; i < length; i++) { int num = nums[i]; if (map.containsKey(num) && i - map.get(num) <= k) { return true; } map.put(num, i); } return false; } }
if(!set.add(nums[i])){
return true;
}
set.add(nums[i]);
}
return false;
}
}
题目三
解法
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
Map
int length = nums.length;
for (int i = 0; i < length; i++) {
int num = nums[i];
if (map.containsKey(num) && i - map.get(num) <= k) {
return true;
}
map.put(num, i);
}
return false;
}
}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~