码迷,mamicode.com
首页 > 其他好文 > 详细

剑指offer题目练习一

时间:2015-11-30 22:10:17      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:

           看见了一道二维数组找数的题,已排好序的数组(从左至右从上到下,都是由小变大的)让找数,瞬间就出思路了,并没有必要去看他的解释,两次二分就搞定了。

     

#include<cstdio>
#include<iostream>

using namespace std;
void sreach(int num[][100], int row, int line, int goal)
{
    int i=0,j=row-1,mid;
    while((j-i)>1)
    {
        mid=(i+j)/2;
        if(num[mid][0]>goal) j=mid;
        else i=mid;
    }
    int a,b;
    a = goal>=num[j][0] ? j : i;
    i=0,j=line-1;
    while((j-i)>1)
    {
        mid=(i+j)/2;
        if(num[a][mid]>goal) j=mid;
        else i=mid;
    }
    b = goal==num[a][j] ? j : i;
    cout<<a<<","<<b<<endl;
}
int main()
{
    int n,m;
    int number[100][100];
    while(scanf("%d%d",&m,&n))
    {
        for(int i=0;i<n;i++)
            for(int j=0;j<m;j++)
            scanf("%d",&number[i][j]);
        int x;
        cin>>x;
        sreach(number, n, m, x);
    }
    return 0;
}
/*
6 6
1 2 3 4 5 6
10 12 15 16 18 21
22 23 26 27 29 30
32 33 34 35 36 37
40 41 43 44 47 50
50 51 55 56 57 58
5 5
1 2 3 4 5
10 12 15 16 18
22 23 26 27 29
32 33 34 35 36
40 41 43 44 47
*/

还有一道插入字符串,把空格都换成%D%,直接链表搞定,不让用链表就用JAVA的linkedlist写。

#include<cstdio>
#include<iostream>

using namespace std;

struct node
{
    char data;
    node *next;
}*root;   // 指针没有盘空
void setuplist(char s[])
{
    node *temp,*n;
    n=root;
    int i=0;
    while(s[i]!=\0)
    {
        temp = new node;
        temp->next=NULL;
        temp->data=s[i];
        n->next=temp;
        n=temp;
        i++;
    }
}
void insertwords()
{
    node *n;
    node *temp1,*temp2;
    n=root->next;
    while(n->next)
    {
        if(n->data== )
        {
            n->data=%;
            temp1 = new node;
            temp1->data = d;
            temp2 = new node;
            temp2->data = %;
            temp1->next=temp2;
            temp2->next=n->next;
            n->next=temp1;
        }
        else n=n->next;
    }
}
void del(node *n)
{
    if(n->next) del(n->next);
    delete n;
}
int main()
{
    char s[100];
    while(gets(s))
    {
        root = new node;
        root->next = NULL;
        setuplist(s);
        insertwords();
        node *t=root->next;
        while(t->next)
        {
            cout<<t->data;
            t=t->next;
        }
        cout<<endl;
        del(root);
    }
}

 

剑指offer题目练习一

标签:

原文地址:http://www.cnblogs.com/liboyan/p/5008433.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!