307. 区域和检索 - 数组可修改【中等题】【每日一题】
思路:【树状数组】
这题我选择乖乖记模板,这看不懂呀 看了大佬写的树状数组的介绍,我是谁 我在哪儿 我在干什么~
代码:
class NumArray {
int[] tree;
int lowbit(int x){//求x的二进制最低位的1
return x & -x;
}
int query(int x){//查询x前方(不包括x)所有nums元素和
int ans = 0;
//当前x位置元素和 等于 tree中 所有的 对应 lowbit位元素和
for (int i = x; i > 0 ; i -= lowbit(i)) {
ans += tree[i];
}
return ans;
}
void add(int x,int u){//构建 树状数组
// x表示nums数组对应的元素下标+1,u表示nums数组的元素
//将从x开始,tree中所有的lowbit(i)位置 += u
for (int i = x; i <= n ; i+=lowbit(i)) {
tree[i] += u;
}
}
int[] nums;
int n;
public NumArray(int[] nums){//构造函数初始化nums对象
this.nums = nums;
n = nums.length;;
tree = new int[n+1];
for (int i = 0; i < n; i++) {//遍历nums数组,调用add函数更新树状数组tree
add(i+1,nums[i]);
}
}
public void update(int index,int val){//更新函数 更新nums中对应下标的值
add(index+1,val - nums[index]);
nums[index] = val;
}
public int sumRange(int left,int right){//求和函数 返回nums数组中闭区间[left,right]下标的元素和
return query(right+1) - query(left);
}
}
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* obj.update(index,val);
* int param_2 = obj.sumRange(left,right);
*/
595. 大的国家【简单题】
代码:
# Write your MySQL query statement below
select name,population,area from World where area >= 3000000 || population >= 25000000;
1757. 可回收且低脂的产品【简单题】
代码:
# Write your MySQL query statement below
select product_id from Products where low_fats = 'Y' && recyclable = 'Y';
584. 寻找用户推荐人【简单题】
代码:
# Write your MySQL query statement below
select name from customer where referee_id is NULL || referee_id != 2;
183. 从不订购的客户【简单题】
代码:
# Write your MySQL query statement below
# select c.Name as `Customers`
# from Customers as c
# left join Orders as o
# on c.Id = o.CustomerId
# where o.id is null;
select c.Name as `Customers`
from Customers as c
where c.id not in (
select CustomerId from Orders
);