当你想合并两个不同大小的列表时,最小列表的索引总是比最大列表更早完成迭代,所以你必须使用&&
运算符。
if(list1 != null && list2 != null)
{
int i=0,j=0;
while(i<list1.size() && j<list2.size())
{
// your code
i++;
j++;
}
// when one of them arrived to end of list to loop will not be executed so you need to check
// those conditions
while (i > list.size() && j < list.size())
{
// your code
j++;
}
while (i < list.size() && j > list.size())
{
// your code
i++;
}
所以为了优化,如果假设m
list1中有n
元素,list2中有元素,时间复杂度总是O(m+n),只会执行两个while循环
编辑
OR
和AND
运算符 are Binary Operators
,这意味着它们必须检查它们组合的两个条件,而Not
is Unary 总是需要一个条件来检查。
如果您听说过这些运算符的真值表,那么编译器被编程为基于这些真值工作表,当他看到 || (或运算符)他用 OR 的真值表检查条件,当他看到 && (和运算符)时,他用 AND 的真值表检查条件。并且由于 OR 和 AND 都是二元运算符,这两个条件都将被“判断”,即使其中一个为真。
或真值表
(假设 A 和 B 是语句(条件),而 R 是您对它们执行 OR 时的结果
-------------------------
A | B | R
-------------------------
True | True | True
-------------------------
True | False | True
-------------------------
False| True | True
-------------------------
False| False | False
-------------------------
// so in Or table, when both of the conditions are false the result is False
// while when one of them is true the result is True
和真值表
(假设 A 和 B 是 statemnts (条件),R 是你做 And 时的结果
-------------------------
A | B | R
-------------------------
True | True | True
-------------------------
True | False | False
-------------------------
False| True | False
-------------------------
False| False | False
-------------------------
// so in And table, when both of the conditions are true the result is True
// while when one of them is false the result is False
我希望现在你明白为什么即使其中一个为真,也必须检查这两个条件。例如,假设你有两个条件 A 和 B,你对它们执行 OR 并假设 A 为假
if (A || B)
// some code here
在这种情况下,它取决于条件 B,如果 B 为假,则不会执行代码,如果 B 为真,则将执行代码。
我知道你问为什么如果 A 为真,它仍在检查 B 条件,所以这是因为 OR 是二元运算符。