求数组中最大的异或值 20171013

本文介绍了一种寻找整数序列中连续子序列的最大幸运数的算法。幸运数定义为序列中最大与次大元素的异或值。文章通过示例说明了如何利用栈和双端队列实现该算法,并提供了Python及C++代码实现。

Suppose you have an integer sequence, we define a lucky number as a special integer which is the XOR value of the sequence’s greatest and strict second greatest element. For example, in [1,2,3,3], 3 is the greatest element and 2 is the strict second greatest one, even though we have two 3 at the same time; so the lucky number is 2 xor 3 = 1.
Now given an N-length integer sequence, please find out the maximum lucky number of all continuous subsequences.

输入描述:
The first line is an integer n, representing the length of the value of V[i](1 <= V[i] <= 10^8) in the sequence respectively. We’ll ensure that there are at least two different values from V[1] to V[n. Define the continuous subsequence as [V[1],V[l+1],V[l+2], … ,V[r]] ( 1 <= l <= r <= n)
30% small input: 2 <= n <= 10
40% medium input: 2 <= n <= 5000
30% large input: 2 <= n <= 100000

输出描述:
Output the greatest lucky number

示例1:

输入
5
5 2 1 4 3

输出
7

python代码

array_length = raw_input()
array = raw_input()
num = [int(n) for n in array.split()]

q = []

ans = -999
for value in num:
    while q and q[-1] <= value:#最大的情况
        ans = max(ans,q[-1]^value)
        q.pop()
    if q:#次大的情况
        ans = max(ans,q[-1]^value)
    q.append(value)
print ans

c++代码

#include<iostream>
#include<stdio.h>
#include<deque>
using namespace std;
deque<int>q;
int main(){
    int i, x, ans = -999,n;
    scanf("%d",&n);
    for(i=1;i<=n;i++)
    {
        scanf("%d",&x);
        while(!q.empty()&&q.back()<=x)
        {
            ans = max(ans,q.back()^x);
            q.pop_back();
        }
        if(q.size()>1) ans= max(ans,q.back()^x);
        q.push_back(x);
    }
    printf("%d",ans);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值