当前位置:网站首页>[leetcode question brushing day 34] 540 Unique element in array, 384 Disrupt array, 202 Happy number, 149 Maximum number of points on a line
[leetcode question brushing day 34] 540 Unique element in array, 384 Disrupt array, 202 Happy number, 149 Maximum number of points on a line
2022-07-03 03:21:00 【tomly2020】
Day 34
540 A single element in an ordered array
Give you an ordered array of integers only , Each of these elements will appear twice , Only one number will appear once .
Please find and return the number that only appears once .
The solution you design must meet O(log n)
Time complexity and O(1)
Spatial complexity .
Method
Because all the elements in the array appear twice , Only one element appears once , If we don't consider the element that appears only once , Then according to the subscript of the array , Elements in even positions always repeat the first element of the element , And the element in odd position always repeats the second element of the element . When we introduce this element that appears only once , After this element , The law becomes The odd position is the first element of the repeating element , The element at the even position is the second element of the repeating element . Take advantage of this feature , We can use binary search to deal with this problem , When mid
When it's even , Let's compare mid
and mid+1
Whether it is equal or not , If equal , It shows that the only element that appears once is mid
Back , Otherwise, it will be mid
front ; In the same way mid
When it's an odd number , We compare mid
and mid-1
that will do , If mid
and mid-1
The elements in position are equal , It indicates that the only element that appears once is mid
Back , Otherwise, in the mid
front .
class Solution {
public int singleNonDuplicate(int[] nums) {
int l = 0, r = nums.length - 1;
while (l <= r){
int mid = (l + r) >> 1;
if ((mid & 1) == 1){
if (nums[mid - 1] == nums[mid]) l = mid + 1;
else r = mid - 1;
}
else{
if (mid + 1 < nums.length && nums[mid] == nums[mid + 1]) l = mid + 1;
else r = mid - 1;
}
}
return nums[l];
}
}
384 Scramble the array
Give you an array of integers nums
, Design algorithms to scramble an array without repeating elements . After the disruption , All permutations of the array should be And so on Of .
Realization Solution
class:
Solution(int[] nums)
Using integer arraysnums
Initialize objectint[] reset()
Reset the array to its initial state and returnint[] shuffle()
Returns the result of randomly scrambling the array
Method
For each position on the number , We generate a 0
To length - 1
The random number , Then let it exchange with the number in that position , Do this for each number in the array .
class Solution {
private int[] nums;
private int length;
private Random rand;
public Solution(int[] nums) {
this.nums = nums;
rand = new Random(2333);
}
public int[] reset() {
return nums;
}
public int[] shuffle() {
int[] res = nums.clone();
for (int i = 0; i < res.length; ++i){
int exchange = rand.nextInt(res.length);
int temp = 0;
temp = res[i];res[i] = res[exchange];res[exchange] = temp;
}
return res;
}
}
202 Happy number
Write an algorithm to judge a number n
Is it a happy number .
「 Happy number 」 Defined as :
For a positive integer , Replace the number with the sum of the squares of the numbers in each of its positions .
Then repeat the process until the number becomes 1, It could be Infinite loop But it doesn't change 1.
If this process The result is 1, So this number is the happy number .
If n
yes Happy number Just go back to true
; No , Then return to false
.
Method
Simulation operation 6
Time , If it's not happy numbers , return false
, Otherwise return to true
.
class Solution {
public boolean isHappy(int n) {
int res = 0;
for (int i = 0; i < 6; ++i){
res = 0;
while (n > 0){
res += (n % 10) * (n % 10);
n /= 10;
}
n = res;
if (n == 1) return true;
}
return false;
}
}
149 The most points on the line
Give you an array points
, among points[i] = [xi, yi]
Express X-Y A point on the plane . Find out how many points are in the same line at most .
Method
Just use the most direct method , We maintain a Line->int
Of map
, Used to record the number of points on each line , return map
The maximum value in the .
class Solution {
public int maxPoints(int[][] points) {
if (points.length == 1) return 1;
Map<Line, Integer> map = new HashMap<>();
for (int i = 0; i < points.length - 1; ++i){
for (int j = i + 1; j < points.length; ++j){
int deltaA = points[i][0] - points[j][0];
int deltaB = points[i][1] - points[j][1];
if (deltaA == 0) {
Line k = new Line(0,Integer.MAX_VALUE, 0, points[i]);
map.put(k, map.getOrDefault(k, 1) + 1);
continue;
}
if (deltaB == 0){
Line k = new Line(0,0, Integer.MAX_VALUE, points[i]);
map.put(k, map.getOrDefault(k, 1) + 1);
continue;
}
int flag = getSign(deltaA, deltaB);
int common = GCD(Math.abs(deltaA), Math.abs(deltaB));
Line k = new Line(flag,Math.abs(deltaB) / common, Math.abs(deltaA) / common, points[i]);
map.put(k, map.getOrDefault(k, 1) + 1);
}
}
int res = 0;
for (int i : map.values()) res = Math.max(res, i);
return res;
}
public int GCD(int m, int n){
if (m % n == 0) return n;
return GCD(n, m % n);
}
public int getSign(int a, int b){
if (a * b < 0) return -1;
return 1;
}
}
class Point{
int x;int y;
Point(int[] a){
x = a[0]; y = a[1];}
@Override public boolean equals(Object p){
Point cmp = (Point) p;
return cmp.x == x && cmp.y == y;
}
@Override public int hashCode(){
return x | y;}
}
class Line{
Point startPoint;
int a;
int b;
int flag;
public Line(int f, int _a, int _b, int[] s){
flag = f;a = _a;b = _b;startPoint = new Point(s);}
@Override
public boolean equals(Object k){
Line cmp = (Line)k;
return flag == cmp.flag && cmp.a == a && cmp.b == b && startPoint.equals(cmp.startPoint);
}
@Override
public int hashCode(){
return flag | a | b | startPoint.hashCode();
}
@Override
public String toString(){
return flag + startPoint.x + " " + startPoint.y + " " + a + "/" + b;
}
}
边栏推荐
- Limit of one question per day
- docker安装mysql
- [combinatorics] Application of exponential generating function (multiple set arrangement problem | different balls in different boxes | derivation of exponential generating function of odd / even sequ
- TCP handshake three times and wave four times. Why does TCP need handshake three times and wave four times? TCP connection establishes a failure processing mechanism
- How do you adjust the scope of activerecord Association in rails 3- How do you scope ActiveRecord associations in Rails 3?
- 解决高并发下System.currentTimeMillis卡顿
- labelme标记的文件转换为yolov5格式
- UMI route interception (simple and rough)
- softmax的近似之NCE详解
- MySql实战45讲【事务隔离】
猜你喜欢
[pyg] understand the messagepassing process, GCN demo details
The idea setting code is in UTF-8 idea Properties configuration file Chinese garbled
[Chongqing Guangdong education] cultural and natural heritage reference materials of China University of Geosciences (Wuhan)
VS 2019 配置tensorRT生成engine
The series of hyperbolic function in daily problem
docker安装redis
Idea set method call ignore case
Limit of one question per day
PAT乙级“1104 天长地久”DFS优化思路
MySql实战45讲【SQL查询和更新执行流程】
随机推荐
Variable declarations following if statements
静态网页 和 动态网页的区别 & WEB1.0和WEB2.0的区别 & GET 和 POST 的区别
Learning notes of C programming [compiled by Mr. Tan Haoqiang] (Chapter III sequence programming) 04 C sentence
Spark on yarn资源优化思路笔记
labelimg生成的xml文件转换为voc格式
How to use asp Net MVC identity 2 change password authentication- How To Change Password Validation in ASP. Net MVC Identity 2?
销毁Session和清空指定的属性
Summary of determinant knowledge points in Chapter 1 of Linear Algebra (Jeff's self perception)
将时间戳转为指定格式的时间
Force deduction ----- the minimum path cost in the grid
[mathematical logic] predicate logic (individual word | individual domain | predicate | full name quantifier | existence quantifier | predicate formula | exercise)
PAT乙级常用函数用法总结
Pytorch轻量级可视化工具wandb(local)
Use of El tree search method
[AI practice] Application xgboost Xgbregressor builds air quality prediction model (I)
[combinatorics] Application of exponential generating function (multiple set arrangement problem | different balls in different boxes | derivation of exponential generating function of odd / even sequ
New programmers use the isXXX form to define Boolean types in the morning, and are discouraged in the afternoon?
VS 2019安装及配置opencv
Pat class B common function Usage Summary
@Accessors注解作用指定前缀遵守驼峰命名