Article directory
1. Title
It is known that there is a monochrome screen composed of pixels. Each row has w
pixels. The initial 0
position of all pixels is (0,0).
Now store the pixels of each 32
row in a group according to "each pixel" int
, and then store them length
in a one-dimensional array with a length of .
(x1,y)
We will draw a straight line from point to point on the screen (x2,y)
(that is, the pixel point is modified to 1
), please return the drawn array.
Notice:
- The use case guarantees that the screen width
w
is evenly32
divisible by (i.e. oneint
will not be spread over two lines)
Example 1:
Input: length = 1, w = 32, x1 = 30, x2 = 31, y = 0
Output: [3]
Explanation: Draw a straight line from the 30th to the 31st bit of line 0. The screen binary form is expressed as [ 00000000000000000000000000000011], so [3] is returned
Example 2:
Input: length = 3, w = 96, x1 = 0, x2 = 95, y = 0
Output: [-1, -1, -1]
Explanation: Since the int type of binary 11111111111111111111111111111111 represents -1, [-1 is returned ,-1,-1]
hint:
1 <= length <= 10^5
1 <= w <= 3 * 10^5
0 <= x1 <= x2 < w
0 <= y <= 10
Click here to jump to the question .
2. Java problem solving
After determining the left and right endpoints, assign values based on the positions. The specific code is as follows:
class Solution {
public int[] drawLine(int length, int w, int x1, int x2, int y) {
int[] ans = new int[length];
int col = w / 32, start = x1 / 32 + y * col, end = x2 / 32 + y * col;
int left = (x1 % 32 == 0 ? 0 : 1 << (32 - x1 % 32)) - 1;
int right = -(1 << (31 - x2 % 32));
if (start == end) ans[start] = left + right + 1;
else {
ans[start] = left;
for (int i = start + 1; i < end; i++) ans[i] = -1;
ans[end] = right;
}
return ans;
}
}
- Time: 0 ms, beats 100.00% of users using Java
- Memory: 40.81 MB, beats 95.08% of users using Java