如何在python的未排序数组中找到两个重复元素

时间:2019-07-13 05:41:50

标签: python arrays data-structures

在这个问题中,我必须从一个数组中的1-N个整数中找到重复项,因为N + 2大小的数组中没有N个整数,下面是我的代码和显示的错误,

请告诉我哪里错了

def find_duplicates(a,n):
    for i in range(n+2):
        if(a[abs(a[i])]>0):
            a[abs(a[i])]= - a[abs(a[i])]
        else:
            print(abs(a[i]), end= " ")
    print("\n")

if __name__ =='__main__':
    cases=int(input())
    for _ in range(cases):
        n=int(input())
        a=list(map(int,input().strip().split()))[:n+2]
        find_duplicates(a,n)

错误是

答案错误。 !! 您的代码可能不适用于多个测试用例(TC)。 您的代码失败的第一个测试用例:

Input:
2
1 1 2 2

Its Correct output is:
1 2

And Your Code's output is:

1 2 4 2 8 15 3 6 2 1 7 6 19 5 7 16 9 2 2 4 35 30 30 2...

1 个答案:

答案 0 :(得分:0)

您的代码已经有效,您可以看到前两个输出是正确的“ 1 2”。但是,问题是您将测试用例的所有输出打印在一行中,这可能会导致错误。在解决新的测试用例之前,请尝试进入新的一行,如下所示:

class A extends Component {
    state = {
        BClassProperties: {
            goldAmount: '1',
            silverAmount: '2'
        }
    }

    onBChange = (goldAmount, silverAmount) => {
        const oldBClassProperties = this.state.BClassProperties;

        let newBClassProperties = {...oldBClassProperties};

        newBClassProperties.goldAmount = goldAmount;
        newBClassProperties.silverAmount = silverAmount;

        this.setState({BClassProperties: newBClassProperties})
    }

    render () {
        return (
           <B 
              goldAmount = {this.state.BClassProperties.goldAmount} 
              silverAmount = {this.state.BClassProperties.silverAmount} 
              onChange={this.onBChange}
           />
        )
    }
}

class B extends Component {

onGoldChange = (event) => {
    this.props.onChange(event.target.value, this.props.silverAmount);
};

onSilverChange = (event) => {
    this.props.onChange(this.props.goldAmount, event.target.value);
};

render () {

    return (
        <React.Fragment>
            <input placeholder={"gold"} value={this.props.goldAmount} onChange={this.onGoldChange} />
            <input placeholder={"silver"} value={this.props.silverAmount} onChange={this.onSilverChange} />
        </React.Fragment>
    )
}
}  
相关问题