给定X个整数和整数Q的P,检查P是否包含数字1,2,...,Q。
例如,给定以下数组P和Q = 3
P[0] = 1
P[1] = 1
P[2] = 2
P[3] = 3
P[4] = 3
该函数应返回True。
以下是我的所得,但我不确定我是否正确?
def solution(P, Q):
n = len(P)
for i in xrange(n - 1):
if (P[i] + 1 < P[i + 1]):
return False
if (P[0] != 1 and P[n - 1] != Q):
return False
else:
return True
答案 0 :(得分:3)
将数组转换为集合,并将集合与1到K之间的所有整数集合进行比较:
// Delegate submit action
$(document).on('submit', 'form', function () {
var validate = true;
var unanswered = new Array();
// Loop through available sets
$('.option').each(function () {
// Question text
var question = $(this).prev();
// Validate
if (!$(this).find('input').is(':checked')) {
// Didn't validate ... dispaly alert or do something
unanswered.push(question.text());
question.css('color', 'red'); // Highlight unanswered question
validate = false;
}
});
if (unanswered.length > 0) {
msg = "Please answer the following questions:\n" + unanswered.join('\n');
alert(msg);
}
return validate;
});
作为额外的奖励,set(A)==set(range(1,K+1))
不再需要排序。
答案 1 :(得分:0)
当我理解你的问题时,数组需要增加1或从i增加到i + 1。因此,您需要更改if语句中的符号。
def solution(A, K):
n = len(A)
for i in xrange(n - 1):
if (A[i] != A[i + 1] and A[i] + 1 != A[i + 1]):
return False
if (A[0] != 1 or A[n - 1] != K):
return False
else:
return True
>>>solution([1,2,3],3)
True
>>>solution([1,2,2,3,3],3)
True
>>>solution([1,2,3],4)
False
>>>solution([1,2,3],2)
False
答案 2 :(得分:0)
def solution(A, K):
n = len(A)
for i in range(K-1):
if (A[i] + 1 < A[i + 1]):
return False
if (A[0] != 1 or A[K - 1] != K):
return False
else:
return True