[心得]面试题分析与整理6

21.快速寻找满足条件的两个数(编程之美176)(面试金典323)

#include 
using namespace std;
void printPairSum(int *a, int n, int sum);

int main()
{
    int arr[]={1,2,3,4,5,6,7,8,9,10,11,12};
    printPairSum(arr, 12, 10);
    return 0;
}

void printPairSum(int *a,int n, int sum)
{
    //qsort(a, n);
    for(int i=0;ifor(int j=n-1;j>i;--j)
        {
            if(a[i]+a[j]==sum)
            {
                cout<<"found pair:\t"<"\t"<break;
            }
        }
    }
}

22.分割数组使得两部分之和最接近
此为编程之美2.18原题
又是一个动态规划题

for(int k=1;k<=2*n;k++)
{
    for(int i=1;i<=k&&i<=n;i++)
        for(int v=1;v<=sum/2;v+1)
        {
            if(v>=arr[k] && isOK[i-1][v-arr[k]))
                isOK[i][v]=TRUE;
        }
}       

23.从1到n中1出现的次数
编程之美2.1原题

int count(int v)
{
    int num=0;
    while(v)
    {
        num +=v&0x01;
        v>>1;
    }
    return num;
}    

24.用双队列实现一个栈
面试金典142页原题

import java.util.Stack;

/**
 * Created by topcoder on 2016/10/6.
 */
public class MyQueue {
    Stack stackNewest, stackOldest;

    public MyQueue()
    {
        stackNewest = new Stack();
        stackOldest = new Stack();
    }

    public int size()
    {
        return stackNewest.size() + stackOldest.size();
    }

    public void add(T value)
    {
        stackNewest.push(value);
    }
    public void shiftStacks()
    {
        if(stackOldest.isEmpty())
        {
            while(!stackNewest.isEmpty())
            {
                stackOldest.push(stackNewest.pop());
            }
        }
    }

    public T peek()
    {
        shiftStacks();
        return stackOldest.peek();
    }

    public T remote()
    {
        shiftStacks();
        return stackOldest.peek()
    }
}

你可能感兴趣的:(面试经验)