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

leetcode1:线性表

时间:2015-09-09 22:47:57      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:

//定义二维数组
int
**array = new int*[row_num]; for(int i=0;i<row_num;i++) { array[i] = new int[col_num]; }
vector
<vector<int>> v2(row_num,vector<int>(col_num,0));
//删除排好序数组中重复的数据,返回剩余数组的长度

//int A[]: input array
//len: the array length
//dup: the times that duplicates can be allowed
//return the length of the result array

int removeDuplicate(int A[],int len,int dup)
{
    if(len <= dup)
        return len;
    
    int index = dup;
    for(int i=dup;i<len;i++)
    {
        if(A[index-dup] != A[i])
        {
            A[index++] = A[i];
        }
    }
    return index;
}

int main()
{
    int A[] = {1,1,1,2,2,3,4,4,4}; 
    std::cout << removeDuplicate(A,9,1) << " ";
    std::cout << removeDuplicate(A,9,2) << " ";    
    std::cout << removeDuplicate(A,9,3) << " ";
    return 0;
}
/*******************************************
binary_search to find a target from a Rotated Array
len: the length of A[]
********************************************/
int binary_search(int A[],int len,int target)
{
    if(len <= 0)
        return -1;
    int first = 0;
    int last = len;
    int mid;
    while(first != last)
    {
        mid = (first + last)/2;

        if(A[mid] == target)
            return mid;

        if(A[first] <= A[mid])
        {
            if(A[first] <= target && target < A[mid])
                last = mid;
            else
                first = mid + 1;
        }
        else
        {
            if(A[mid] < target && target <= A[last - 1])
                first = mid + 1;
            else
                last = mid;
        }    
    }
    return -1;
}
int main()
{
    int A[] = {7,8,9,1,2,3,4,5,6};
    for(int i=1;i<10;i++)
    {
        std::cout << binary_search(A,9,i) << " ";
    }
    return 0;
}

 

leetcode1:线性表

标签:

原文地址:http://www.cnblogs.com/wxquare/p/4795917.html

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