Skip to content

Commit 5c21a2b

Browse files
committed
加入 作业代码
1 parent 0b2dd5e commit 5c21a2b

2 files changed

Lines changed: 94 additions & 0 deletions

File tree

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
package WeekOne;
2+
3+
import java.util.ArrayList;
4+
5+
public class Array盛最多水的容器和移动零 {
6+
7+
// LeetCode questionNumber 11
8+
9+
/*
10+
给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。
11+
在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
12+
说明:你不能倾斜容器。
13+
* */
14+
15+
public static void main(String[] args) {
16+
// 盛最多水的容器
17+
/* int[] height = new int[]{1, 8, 6, 2, 5, 4, 8, 3, 7};
18+
System.out.println(maxArea(height));*/
19+
20+
// 移动零 0,1,0,3,12
21+
int[] nums = new int[]{0,1,0,3,12};
22+
moveZeroe(nums);
23+
}
24+
25+
26+
27+
28+
public static void moveZeroe(int[] nums) {
29+
30+
// 第一次写的时候是 开辟新的数组空间 然后!= 0 的加入 最后尾部加入0 效率非常的低
31+
32+
// 这是最快的 时间复杂度 n
33+
if(nums==null) {
34+
return;
35+
}
36+
//两个指针i和j
37+
int j = 0;
38+
for(int i=0;i<nums.length;i++) {
39+
//当前元素!=0,就把其交换到左边,等于0的交换到右边
40+
if(nums[i]!=0) {
41+
int tmp = nums[i];
42+
nums[i] = nums[j];
43+
nums[j++] = tmp;
44+
}
45+
}
46+
}
47+
48+
49+
50+
/**
51+
* 计算容器
52+
*
53+
* @param height
54+
* @return
55+
*/
56+
public static int maxArea(int[] height) {
57+
// 方案一 n*n 两次的for
58+
/*
59+
int maxValue = 0;
60+
for (int i = 0; i < height.length; i++) {
61+
for (int iTwo = 0; iTwo < height.length; iTwo++) {
62+
int waterHeight = Math.min(height[i], height[iTwo]);
63+
System.out.println("高度的差是" + waterHeight);
64+
System.out.println("iTwo - i的值是" +"iTwo "+iTwo+" i的值是 "+i+ (iTwo - i));
65+
int maxValueCapacity = (iTwo - i) * waterHeight;
66+
System.out.println("maxValue 的值是" + maxValueCapacity);
67+
maxValue = Math.max(maxValueCapacity, maxValue);
68+
}
69+
}
70+
return maxValue;
71+
*/
72+
// 方案二 折中 计算 时间复杂度 n
73+
// 起始的地址
74+
int i = 0,
75+
// 末尾开始
76+
j = height.length - 1,
77+
// 标记值
78+
res = 0;
79+
80+
// max (a >= b) ? a : b
81+
while (i < j) {
82+
res = height[i] < height[j] ?
83+
Math.max(res, (j - i) * height[i++]) :
84+
Math.max(res, (j - i) * height[j--]);
85+
}
86+
return res;
87+
}
88+
89+
90+
91+
92+
93+
94+
}
Binary file not shown.

0 commit comments

Comments
 (0)