您的位置:首页 > 运维架构 > Linux

Linux 3+1班的一道机试题

2017-04-10 10:26 267 查看
问题描述:有一个整型数组a,共有1000个元素,即int a[1000]={1, 2, 3, 4...1000},现在请设计一个算法,将每隔两个的数组元素删除,求最后的剩余一个元素的下标和值。如果到结尾的话,从头开始,循环删除。例如有十个数据时

a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

删除的顺序是3, 6, 9, 2, 7, 1, 8, 5, 10

剩余的一个元素是4,它的下标是3.
算法思想:用index来表示数组的下标,count表示已经删除的元素个数,如果count==N-1表示只剩下一个元素没有删除,这个时候退出循环。

具体实现:

#include <stdio.h>

#define N 1000

int main()
{
    int a[N], i, count, index;

    for(i = 0; i < N; i++) {
        a[i] = i+1;
    }
    
    index = 0;
    count = 0;
    while(1) {
        /*找到第一个不是0的index下标*/
        while(a[index] == 0) {
            index++;
            if(index == N) {
                index = 0;
            }
        }
        if(count == N-1) {
            i = index;
            break;
        }
        /*index下标加一,一直找到一个不为0的下标,表示空一个数字*/
        index++;
        if(index == N) {
            index = 0;
        }
        while(a[index] == 0) {
            index++;
            if(index == N) {
                index = 0;
            }
        }
        /*index下标加一,一直找到一个不为0的下标,表示空第二个数字*/
        index++;
        if(index == N) {
            index = 0;
        }
        while(a[index] == 0) {
            index++;
            if(index == N) {
                index = 0;
            }
        }
        a[index] = 0;
        count++;
    }

    printf("a[%d] = %d\n", i, a[i]);

    return 0;
}
 

结果:

a[603]=604


<script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script>

阅读(726) | 评论(0) | 转发(0) |

0
上一篇:关于sscanf的用法

下一篇:linux下解压缩命令大全

相关热门文章
test123

编写安全代码——小心有符号数...

彻底搞定C语言指针详解-完整版...

使用openssl api进行加密解密...

一段自己打印自己的c程序...

linux dhcp peizhi roc

关于Unix文件的软链接

求教这个命令什么意思,我是新...

sed -e "/grep/d" 是什么意思...

谁能够帮我解决LINUX 2.6 10...

给主人留下些什么吧!~~

评论热议
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: