Java 计数元素置换检查
在编码置换检查问题中:Java 计数元素置换检查,java,Java,在编码置换检查问题中: A non-empty zero-indexed array A consisting of N integers is given. A permutation is a sequence containing each element from 1 to N once, and only once. For example, array A such that: A[0] = 4 A[1] = 1 A[2] = 3 A[3] = 2 i
A non-empty zero-indexed array A consisting of N integers is given.
A permutation is a sequence containing each element from 1 to N once, and only once.
For example, array A such that:
A[0] = 4
A[1] = 1
A[2] = 3
A[3] = 2
is a permutation, but array A such that:
A[0] = 4
A[1] = 1
A[2] = 3
is not a permutation.
The goal is to check whether array A is a permutation.
Write a function:
class Solution { public int solution(int[] A); }
that, given a zero-indexed array A, returns 1 if array A is a permutation and 0 if it is not.
For example, given array A such that:
A[0] = 4
A[1] = 1
A[2] = 3
A[3] = 2
the function should return 1.
Given array A such that:
A[0] = 4
A[1] = 1
A[2] = 3
the function should return 0.
Assume that:
N is an integer within the range [1..100,000];
each element of array A is an integer within the range [1..1,000,000,000].
Complexity:
expected worst-case time complexity is O(N);
expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
这是我的解决方案,但我有一个错误。我觉得,在代码正常工作之前,我需要检查一个额外的条件。当使用这样的数组进行测试时:A[4,1,3},它返回1而不是0。我还需要测试什么才能使此代码正常工作?我缺少它,因为我不明白为什么A[]{4,1,3}不是置换,为什么A[]{4,1,3,2}是问题中的一个排列。如果有人能解释这一点,我也许能够解决我的问题。现在,我确实修改了它,以便在我的eclipse上工作,经过测试,但在可编码性上,我仍然不断得到关于以下行的错误:counter[a[I]]+=1;有人知道为什么会这样吗?数组超出了界限,但我在EclipseIDE上没有得到这个错误。
谢谢
根据排列的定义,每个数字中必须正好有一个,请参见 首先尝试使用双嵌套循环,这不是要求的答案,因为它需要^2复杂性,但它是最简单的算法
一个问题是您没有使用计数器数组,您正在设置但没有读取值。我不太明白为什么它的大小有[0]*A.length.A[0]不是特别的,因为3,2,4,1或1,2,3,4可能是有效的排列。这个问题的措辞有点混乱。它实际上希望您检查数组是否包含1..N个整数,没有重复或丢失的数字
class Solution {
public int solution(int[] A) {
// write your code in Java SE 7
int[] count = new int[A.length];
for (int i = 0; i < A.length; i++) {
int x = A[i]-1;
if (x >= A.length) return 0;
int check = count[x];
if (check > 0) return 0;
count[x] = 1;
}
return 1;
}
}
以下几点可以改进您解决此问题的方法: max变量实际上不是必需的,因为您可以将数组的值与数组的长度进行比较。如果其中任何一个值超过了长度,您只需中断程序并返回0即可 我不清楚您试图用计数器数组实现什么。当您实例化它时,您是用长度为a乘以[0]来实例化它。考虑到[0]可以是任何值,或者在示例问题a[0]中可以是1,2,3,4您不知道计数器数组的长度应该是多少。如果希望计数器数组的长度与我在解决方案中使用的a数组的长度相同,请使用以下命令:
int[] counter = new int[A.length];
概念之前发生的是有趣的,但是你必须考虑数组可以是任何长度。所以如果我们有{2,3,2,4,5,6 }的数组。,则您的occurBefore值将为2,然后将2与3进行比较,将occurBefore更改为3,然后将2与3进行比较。即使数组中存在两次2,您的occurBefore比较也不会显示这一点
提示:您可以使用2个for循环,一个用于用合法值填充数组,一个用于确认填充的数组包含有效排列所需的1->N个数字。这很好 排序数组 检查每对相邻元素。如果右元素!=左元素+1, 那么这个数组就不是一个排列public class permutation {
public static void main(String[] args) {
int[] A={2,3,7,4,5,8,6,9,10,11};
Arrays.sort(A);
boolean perm = true;
for (int i=0; i<A.length-1; i++){
if(A[i+1]!= A[i]+1 ){
perm = false;
}
}
System.out.println(perm);
}
}
100%结果:用于PermCheck Codibility的PHP代码
100/%用于PHP PermCheck可编程性,更优化
简单的PHP100/100解决方案
function solution($A) {
$count = count($A);
if (count(array_unique($A)) != $count) return 0;
$sum = array_sum($A);
$should_be = 0;
for ($i = 1; $i <= $count; $i++) {
$should_be += $i;
}
return intval($sum == $should_be);
}
我使用了Set作为解决方案:
import java.util.*;
class Solution {
public int solution(int[] A) {
final Set perm = new HashSet();
final int size = A.length;
for(int number : A)
{
if(number > size)
return 0;
perm.add(number);
}
if(perm.size() == A.length)
return 1;
else
return 0;
}
}
这是一个100/100的Scala解决方案。发现它在Scala中更优雅
object Solution {
def solution(A: Array[Int]): Int = {
if (A.max == A.length && A.distinct.size == A.length)
1
else
0
}
}
该溶液的可变性得分为100分:
/**
* https://codility.com/demo/results/demoYEU94K-8FU/ 100
*/
public class PermCheck {
public static final int NOT_PERMUTATION = 0;
public static final int PERMUTATION = 1;
// (4,1,3,2) = 1
// (4,1,3) = 0
// (1) = 1
// () = 1
// (2) = 0
public int solution(int[] A) {
// write your code in Java SE 8
int[] mark = new int[A.length + 1];
for (int i = 0; i < A.length; ++i) {
int value = A[i];
if(value >= mark.length) {
return NOT_PERMUTATION;
}
if(mark[value] == 0) {
mark[value]=1;
} else {
return NOT_PERMUTATION;
}
}
return PERMUTATION;
}
}
您也可以在此处看到:
还有其他一些。这是我在Scala中的解决方案: }
这个解决方案得到100并且是完整的如果按照任务描述,排列是一个包含从1到N的每个元素的序列,一次,而且只有一次,那么可以这样做:
public int solution(int... A) {
Set<Integer> set = new HashSet<>();
// calculating sum of permutation elements
int sum = A.length * (A.length +1) /2;
for(int i=0; i<A.length;i++){
set.add(A[i]);
sum -=A[i];
}
// return 0 if either sizes don't much or there was some
// number/s missing in permutation and thus sum !=0;
return ((set.size() == A.length) && sum ==0)? 1 : 0;
}
红宝石100%:
def solution(a)
values = a.uniq
is_ok = 0
if values.length == a.length
is_ok = (a.length == a.max) ? 1 : 0
end
is_ok
end
短码很漂亮。取一个向量,将它们全部标记为1。然后对给定向量进行迭代,并将当前位标记为0。现在找到非零元素。如果存在,则返回0,否则返回1 我对Python 3.6问题的看法……基于各种想法,非常感谢
def solution(A):
# write your code in Python 3.6
if len(A) == 0:
return 0
max_element = max(A)
if max_element - len(A) > 1:
return 0
actual_sum = sum(A)
check_sum = sum(range(1, len(set(A)) + 1))
if actual_sum != check_sum:
return 0
return 1
Swift 4解决方案
Python解决方案,让我获得100%的结果
def solution(A):
le = len(A)
A = list(set(A))
if le != len(A):
return 0
le = len(A)
if le != max(A):
return 0
return 1
您可以使用前n个自然数的一个线性和 如果a.sum==a.size*a.size+1/2&&a.max==a.distinct.length 1,则为0
这也提供了100%的可编码性,但这里没有同时使用数组所有基于异或的检查,但在c中没有额外的内存使用代码{ int N=A.长度; 返回N*N+1/2-IntStream.ofA.distinct.filteri->i>=1&&i 带描述的python解决方案-易于理解-
def solution(ar):
"""
https://app.codility.com/demo/results/trainingEBQW3A-6N8/
100%
idea is use xor - xor of two same number cancel the same bits and make that to zero
do xor of all elements of array
do xor of 1 to length plus 1
at last xor of all should be zero
A non-empty array A consisting of N integers is given.
A permutation is a sequence containing each element from 1 to N once, and only once.
:param ar:
:return:
"""
xor_sum = 0
# xor of 1 to len ar
# xor of all elements of existing array
for index in range(1, len(ar) + 1):
xor_sum = xor_sum ^ index ^ ar[index - 1]
# at the end xor sum should be zero
if xor_sum == 0:
return 1
else:
return 0
arr = [1, 2]
result = solution(arr)
print("Sol " + str(result))
这是得分100%的Java解决方案
使用JavaScript的简单解决方案100%经过测试 Javascript:这是我的两个解决方案,都具有时间复杂性:ON或ON*logN
//ask Score 100% | Correctness 100% | Performance 100%
function solution(A) {
let arr = [];
for (let i = 0; i < A.length; i++) {
if (arr[A[i] - 1] == 1) return 0; //exit for duplicated
arr[A[i] - 1] = 1;
}
if (arr[0] == 1)
for (let i = 0; i < arr.length; i++) {
if (!arr[i]) return 0; //no number in this position
}
else return 0; // first number not is 1;
return 1;
}
//ask Score 100% | Correctness 100% | Performance 100%
function solution(A) {
A.sort((a, b) => a - b);
for (let i = 0; i < A.length; i++) {
if (A[i] != i + 1) return 0; //isn't a number for this position
}
return 1;
}
您好,谢谢您的输入。我可以修改A[0]*A.length部分。我的大问题是为什么A[0]=4,A[1]=1,A[2]=3不是排列?这些数字出现过一次。这是我仍然不清楚的部分。您需要A[0]=4,A[1]=1,A[2]=3,A[3]=2使其成为排列。如果将排列视为排列数字1、2、3、4的一种方式,则每个数字必须恰好出现一次。请问我如何为计数器数组分配更好的大小?Y
你提到了为什么itz大小有[0]*A长度?嗯,我试了一下,但没有得到答案。有更好的方法来解决这个问题吗?我只需要使用int[]counter=newint[A.length];但实际上不确定算法的工作方式以及计数器数组的用途。计数器[A[i]]+=1的问题在于,数组的索引从0开始,长度为-1。所以A[i]=4,计数器有4个元素。计数器[A[i]]将导致错误。您可能需要计数器[A[i]-1]。我不理解循环结束后的最后一个条件。你能解释一下吗?这不是已经被循环中的两个if条件覆盖了吗?唯一的问题是这是在logn上的解决方案。如果你在排序数组,你不需要再次遍历数组,你只需要检查第一个和最后一个元素,第一个元素必须等于1,最后一个元素必须等于A.length。无论如何,这不是O n,就时间而言,这可能是日志n上的最佳情况,因为array.sort在时间复杂度方面没有打开。@moxi回答不正确。数组可以有重复的元素,因此不是一个排列,即所有元素都是唯一的,并且仍然有第一个和最后一个元素。tas排序数组将作为正确的解决方案工作,但在效率测试中会失败。换句话说,当数组中的元素超过1000000个时,它将进入超时状态,这只是测试用例中的一小部分。请在答案中添加一些信息,例如您正在做什么,为什么,为什么您的答案是正确的,或者您的答案与其他答案有什么不同。因为只有代码答案没有多大帮助。N记录N的复杂性。对于较大的数字,此解决方案可能在其他语言中不起作用,因为N是[1..100000]范围内的整数;数组A的每个元素都是[1..100000000]范围内的整数一个小优化:如果!perm.addnumber{return 0;}在这里输入代码我认为这是迄今为止最好的Python解决方案。
def solution(a)
values = a.uniq
is_ok = 0
if values.length == a.length
is_ok = (a.length == a.max) ? 1 : 0
end
is_ok
end
public int solution(int[]A) {
Arrays.sort(A);
for(int i=0; i<A.length;i++) {
if (A[i]!=i+1) {
System.out.println("0");
return 0;
}
}
System.out.println("1");
return 1;
}
#include <set>
#include <vector>
#include <iostream>
using namespace std;
int solution(vector<int> &A) {
vector<int> range(A.size(),1);
for(unsigned int i=0; i < A.size(); i++){
if(A[i] <= A.size() && A[i] > 0)
range[A[i]-1] = 0;
}
for(unsigned int i=0; i < A.size(); i++)
if(range[i]) return 0;
return 1;
}
int main(){
vector<int> A = {4, 1, 3, 2};
cout << solution(A);
return 0;
}
def solution(A):
# write your code in Python 3.6
if len(A) == 0:
return 0
max_element = max(A)
if max_element - len(A) > 1:
return 0
actual_sum = sum(A)
check_sum = sum(range(1, len(set(A)) + 1))
if actual_sum != check_sum:
return 0
return 1
public func solution(_ A : inout [Int]) -> Int{
let resultValue = 1
A = A.sorted{$0 > $1}
let lastIndex : Int = A.last ?? 0
if lastIndex != 1 {
return 0
}
for index in stride(from: 0, to: A.count - 1, by: 1){
if (A[index] - 1) != A[index + 1]{
return 0
}
}
return resultValue
}
def solution(A):
le = len(A)
A = list(set(A))
if le != len(A):
return 0
le = len(A)
if le != max(A):
return 0
return 1
public int solution(int[] A)
{
int xorsum = 0;
for (int i = 0; i < A.Length; i++)
{
xorsum = (i + 1) ^ A[i] ^ xorsum;
}
if (xorsum > 0)
return 0;
return 1;
}
def solution(ar):
"""
https://app.codility.com/demo/results/trainingEBQW3A-6N8/
100%
idea is use xor - xor of two same number cancel the same bits and make that to zero
do xor of all elements of array
do xor of 1 to length plus 1
at last xor of all should be zero
A non-empty array A consisting of N integers is given.
A permutation is a sequence containing each element from 1 to N once, and only once.
:param ar:
:return:
"""
xor_sum = 0
# xor of 1 to len ar
# xor of all elements of existing array
for index in range(1, len(ar) + 1):
xor_sum = xor_sum ^ index ^ ar[index - 1]
# at the end xor sum should be zero
if xor_sum == 0:
return 1
else:
return 0
arr = [1, 2]
result = solution(arr)
print("Sol " + str(result))
import java.util.*;
class Solution
{
public int solution(int[] A)
{
Arrays.sort(A);
// to remove duplicates
Set<Integer> set = new HashSet<Integer>();
for(int i : A)
{
set.add(i);
}
List<Integer> list = new ArrayList<>(set);
int array_size = A.length;
int value = 1;
if (array_size != list.size() || list.get(0) != 1 || list.get(list.size() - 1) != array_size)
value = 0;
return value;
}
}
function solution(A) {
A.sort(function(a, b){return a-b});
let bool = 1;
if(A[0] === 1) {
for(let i=0; i<A.length; i++) {
if((i+1) < A.length) {
if(A[i] != A[i+1] - 1) {
bool = 0;
}
}
}
} else {
bool = 0;
}
return bool;
}
//ask Score 100% | Correctness 100% | Performance 100%
function solution(A) {
let arr = [];
for (let i = 0; i < A.length; i++) {
if (arr[A[i] - 1] == 1) return 0; //exit for duplicated
arr[A[i] - 1] = 1;
}
if (arr[0] == 1)
for (let i = 0; i < arr.length; i++) {
if (!arr[i]) return 0; //no number in this position
}
else return 0; // first number not is 1;
return 1;
}
//ask Score 100% | Correctness 100% | Performance 100%
function solution(A) {
A.sort((a, b) => a - b);
for (let i = 0; i < A.length; i++) {
if (A[i] != i + 1) return 0; //isn't a number for this position
}
return 1;
}
//Below solution given me 100%
public int solution100(int[] A) {
if (A.length == 0)
return 0;
if (A.length == 1 && A[0] != 1)
return 0;
int len = A.length;
int max = Integer.MIN_VALUE;
Set<Integer> hSet = new HashSet<Integer>();
for (int i = 0; i < A.length; i++) {
if (max < A[i])
max = A[i];
hSet.add(A[i]);
}// for_i
int s_size = hSet.size();
if (s_size == len && max == len)
return 1;
enter code here
return 0;
}