ACM基础之线性结构:一刷 参考答案

Remove Duplicates from a Array

import java.util.Arrays;
import java.util.Scanner;
import java.util.Scanner;
public class Main {
    public static int removeDuplicates(int A[], int n) {
        if (n == 0) return 0;
        int index = 0;
        for (int i = 1; i < n; i++) {
            if (A[index] != A[i])
                A[++index] = A[i];
        }
        return index + 1;
    }

    public static void main(String[] args) {
        Scanner myScan = new Scanner(System.in);
        int arrNum = myScan.nextInt();
        int myArr[] = new int[arrNum];
        for (int i = 0; i < arrNum; i++) {
            myArr[i] = myScan.nextInt();
        }

        Arrays.sort(myArr);

        int index = removeDuplicates(myArr, myArr.length);
        System.out.println(index);
        for (int i = 0; i < index; i++) {
            if (i < index - 1) {
                System.out.print(myArr[i] + " ");
            } else
                System.out.print(myArr[i]);
        }
    }
}

Median of Two Sorted Arrays

参考代码 C++ 李祥
// #include<bits/stdc++.h>

#include<iostream>
#include<algorithm>
#include<vector>
#include<cctype>
#include<cmath>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<queue>
#include<sstream>
using namespace std;

int main(){
    vector<int> a;
    int n;
    cin >> n;
    a.push_back(n);
    stringstream ss;
    string str;
    getline(cin, str);
    ss.clear();
    ss.str(str);
    char c;
    while (ss >> c >> n){
        a.push_back(n);
    }
    cin >> n;
    a.push_back(n);
    getline(cin, str);
    ss.clear();
    ss.str(str);
    while (ss >> c >> n){
        a.push_back(n);
    }
    sort(a.begin(), a.end());
    int mid;
    if (a.size() % 2){
        mid = a.at(a.size() / 2);
    }
    else{
        mid = a.at(a.size() / 2) + a.at(a.size() / 2 - 1);
        mid /= 2;
    }
    cout << "Median is " << mid << endl;
    return EXIT_SUCCESS;
}

 

考试问题(线性表)

参考代码 Java

import java.util.*;
class Student{
    String name;
    float score[]=new float[3];
}
public class Main {
    private static Scanner sc;
    public static void main(String[] args) {
        List<Student> list=new ArrayList<Student>();
        sc = new Scanner(System.in);
        float m;
        m = sc.nextFloat();
        while (sc.hasNext()) {
            Student stu=new Student();
            stu.name=sc.next();
            stu.score[0]=sc.nextFloat();
            stu.score[1]=sc.nextFloat();
            stu.score[2]=sc.nextFloat();
            list.add(stu);
        }

        for(int i=0 ;i<list.size();i++)
        {
            if(list.get(i).score[0]+list.get(i).score[1]+list.get(i).score[2]>=180){
                System.out.println(list.get(i).name+" -- pass exam");
            }
        }
        for(int i=0 ;i<list.size();i++)
        {
            if(list.get(i).score[0]+list.get(i).score[1]+list.get(i).score[2]<180){
                System.out.println(list.get(i).name+" -- not pass exam");
            }
        }
        for(int i=0 ;i<list.size();i++)
        {
            if(list.get(i).score[0]+list.get(i).score[1]+list.get(i).score[2]==300){
                System.out.println(list.get(i).name+" -- 3 x 100.0");
            }
        }
    }
}

C李祥

#include <stdio.h>
#include <stdlib.h>
typedef struct {
    char name[32];
    float mark[3];
} ST;

int main()
{
    ST *all_st;
    float f1, f2, f3;
    int N, i;
    scanf("%d", &N);
    all_st = (ST *)malloc(N * sizeof(ST));
    for (i = 0; i < N; i++){
        scanf("%s %f %f %f", &all_st[i].name, &f1, &f2, &f3);
        all_st[i].mark[0] = f1;
        all_st[i].mark[1] = f2;
        all_st[i].mark[2] = f3;
    }

    for (i = 0; i < N; i++){
        f1 = all_st[i].mark[0] + all_st[i].mark[1] + all_st[i].mark[2];
        if (f1 >= 180.0) {
            printf("%s -- pass exam
", all_st[i].name);
        }
    }

    for (i = 0; i < N; i++){
        f1 = all_st[i].mark[0] + all_st[i].mark[1] + all_st[i].mark[2];
        if (f1 < 180.0) {
            printf("%s -- not pass exam
", all_st[i].name);
        }
    }

    for (i = 0; i < N; i++){
        f1 = all_st[i].mark[0] + all_st[i].mark[1] + all_st[i].mark[2];
        if (f1 >= 300.0) {
            printf("%s -- 3 x 100.0
", all_st[i].name);
        }
    }
    return EXIT_SUCCESS;
}

找相同元素(线性表)

#include<iostream>
using namespace std;
int main()
{
    int n1, n2, n3;
    int i, j, t = 0, b = 0, a = 0;
    int t1 = 0, t2 = 0, t3 = 0;
    int t11 = 0, t22 = 0, t33 = 0;
    cin >> n1;
    int *p1 = new int[n1];
    for (i = 0; i<n1; i++)
        cin >> p1[i];
    cin >> n2;
    int *p2 = new int[n2];
    for (i = 0; i<n2; i++)
        cin >> p2[i];
    cin >> n3;
    int *p3 = new int[n3];
    for (i = 0; i<n3; i++)
        cin >> p3[i];
    int *p11 = new int[n1];
    for (i = 0; i<n1; i++)
    {
        if (p1[i] != p1[i + 1])
        {
            p11[t1] = p1[i];
            t1++;
        }
    }
    int *p22 = new int[n2];
    for (i = 0; i<n2; i++)
    {
        if (p2[i] != p2[i + 1])
        {
            p22[t2] = p2[i];
            t2++;
        }
    }
    int *p33 = new int[n3];
    for (i = 0; i<n3; i++)
    {
        if (p3[i] != p3[i + 1])
        {
            p33[t3] = p3[i];
            t3++;
        }
    }

    int *p111 = new int[n1 + n2];
    for (i = 0; i<t1; i++)
    {
        for (j = 0; j<t2; j++)
        {
            if (p11[i] == p22[j])
            {
                p111[t11] = p11[i];
                t11++;
            }
        }
    }
    int *p = new int[t1 + t2 + t3];
    for (i = 0; i<t11; i++)
    {
        for (j = 0; j<t3; j++)
        {
            if (p111[i] == p33[j])
            {
                p[t33] = p111[i];
                t33++;
            }
        }
    }

    for (i = 0; i<t33; i++)
        cout << p[i] << " ";
}

Java代码

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class Main {
    static Scanner cin = new Scanner(System.in);
    public static void main(String[] args) {
        int an = cin.nextInt();
        List<Integer> aList = new ArrayList<Integer>();
        Map<Integer, Boolean> aMap = new HashMap<Integer, Boolean>();
        for (int i = 0; i < an; i++) {
            int a = cin.nextInt();
            if (aMap.get(a) == null) {
                aList.add(a);
                aMap.put(a, true);
            }
        }
        int bn = cin.nextInt();
        List<Integer> bList = new ArrayList<Integer>();
        Map<Integer, Boolean> bMap = new HashMap<Integer, Boolean>();
        for (int i = 0; i < bn; i++) {
            int b = cin.nextInt();
            if (bMap.get(b) == null) {
                bList.add(b);
                bMap.put(b, true);
            }
        }
        int cn = cin.nextInt();
        List<Integer> cList = new ArrayList<Integer>();
        Map<Integer, Boolean> cMap = new HashMap<Integer, Boolean>();
        for (int i = 0; i < cn; i++) {
            int c = cin.nextInt();
            if (cMap.get(c) == null) {
                cList.add(c);
                cMap.put(c, true);
            }
        }
        List<Integer> list1 = new ArrayList<Integer>();
        Map<Integer, Boolean> map1 = new HashMap<Integer, Boolean>();
        for (int i = 0; i < bList.size(); i++) {
            int t = bList.get(i);
            if (aMap.get(t) != null) {
                list1.add(t);
                map1.put(t, true);
            }
        }
        List<Integer> list2 = new ArrayList<Integer>();
        for (int i = 0; i < cList.size(); i++) {
            int t = cList.get(i);
            if (map1.get(t) != null) {
                list2.add(t);
            }
        }
        Collections.sort(list2);
        for (int i = 0; i < list2.size(); i++) {
            System.out.print(list2.get(i) + " ");
        }
    }
}

 

交换节点(线性表)

提示

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> list1 = new ArrayList<Integer>();
        ArrayList<Integer> list2 = new ArrayList<Integer>();
        Scanner cin = new Scanner(System.in);
        int n = cin.nextInt();
        int a[] = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = cin.nextInt();
            list1.add(a[i]);
        }
        int m = cin.nextInt();
        Collections.swap(list1, m - 1, m);
        for (int i = 0; i < list1.size(); i++) {
            System.out.print(list1.get(i) + " ");
        }
    }
}

----------------

# include <iostream>
typedef int ElemType;
typedef struct LNode{
    ElemType data;
    struct LNode *next;
}LNode, *LinkList;

LinkList CreatList(LinkList L, int n){
    LinkList p, s;
    int i;
    L = new LNode;
    L->next = NULL;
    s = L;
    for (i = n; i > 0; i--)
    {
        p = new LNode;
        std::cin >> p->data;
        p->next = s->next;
        s->next = p;
        s = p;
    }
    s->next = L;
    return L;
}

void ExchangeList(LinkList L, int m) {
    int count = 1;
    ElemType e;
    LinkList cur;
    cur = L->next;
    while (1)  {
        if (count == m) {
            if (cur->next == L) {
                e = L->next->data;
                L->next->data = cur->data;
                cur->data = e;
                break;
            }
            e = cur->next->data;
            cur->next->data = cur->data;
            cur->data = e;
            break;
        }
        cur = cur->next;
        count++;
    }
}

void PrintList(LinkList L){
    LinkList p;
    p = L->next;//如果没有这句就非法输出了一个NULL出现错误报告
    while (p != L) {
        std::cout << p->data;
        if (p->next != L)std::cout << ' ';
        p = p->next;
    }
}
int main(){
    LinkList L;
    int n, m;
    std::cin >> n;
    L = CreatList(L, n);
    //  PrintList(L);
    std::cin >> m;
    ExchangeList(L, m);
    PrintList(L);
    return 0;
}

最快合并链表(线性表)

待完善…

 

Longest Consecutive Sequence

Java 代码

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
    static Scanner cin = new Scanner(System.in);
    static void display(String[] s){
        System.out.print(s[0]);
        for (int i = 1; i < s.length; i++) {
            System.out.print(" "+s[i]);
        }
        System.out.println();
    }

    public static void main(String[] args) {
        String[] s = cin.nextLine().split(" *, *");
        Map<Integer, Boolean> map = new HashMap<Integer, Boolean>();
        int max=Integer.parseInt(s[0]);
        int min=Integer.parseInt(s[0]);
        for (int i = 0; i < s.length; i++) {
            int t = Integer.parseInt(s[i]);
            if(t>max)max=t;
            if(t<min)min=t;
            if(map.get(t)==null){
                map.put(t, true);
            }
        }
        //System.out.println("max="+max+"	min="+min);
        int maxLen=1,maxEnd=min-1,len=0;
        for (int i = min; i <= max; i++) {
            if(map.get(i)!=null){
                len++;
                if(len>maxLen){
                    maxLen=len;
                    maxEnd=i;
                }
            }else{
                len=0;
            }
        }
        for (int i = maxEnd-maxLen+1; i < maxEnd; i++) {
            System.out.print(i+",");
        }
        System.out.println(maxEnd);
        System.out.println(maxLen);
    }
}
完整代码C++ 李祥
#include<iostream>
#include<algorithm>
#include<vector>
#include<cctype>
#include<cmath>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<queue>
#include<sstream>


using namespace std;
int main()
{
    vector<int> numbers;
    int x;
    char c;
    cin >> x;
    numbers.push_back(x);
    string str;
    getline(cin, str);
    stringstream ss;
    ss.clear();
    ss.str(str);
    while (ss >> c >> x){
        numbers.push_back(x);
    }
    sort(numbers.begin(), numbers.end());
    int ms1 = 0, ms2 = 0, mn1 = 1, mn2 = 1;
    for (int i = 1; i<numbers.size(); i++){
        if (numbers[i] - numbers[i - 1] == 1){
            mn2++;
        }
        else{
            if (mn1<mn2){
                mn1 = mn2;
                ms1 = ms2;
            }
            ms2 = i;
            mn2 = 1;
        }
    }
    if (mn1<mn2){
        mn1 = mn2;
        ms1 = ms2;
    }
    for (int i = ms1; i<ms1 + mn1 - 1; i++){
        cout << numbers[i] << ",";
    }
    cout << numbers[ms1 + mn1 - 1] << endl;
    cout << mn1 << endl;
    return EXIT_SUCCESS;
}

Two Sum 数组

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {

    static Scanner cin = new Scanner(System.in);

    static int[] convertStr2Int(String[] s) {
        int[] a = new int[s.length];
        for (int i = 0; i < a.length; i++) {
            a[i] = Integer.parseInt(s[i]);
        }
        return a;
    }

    static void display(String[] s) {
        System.out.print(s[0]);
        for (int i = 1; i < s.length; i++) {
            System.out.print(" " + s[i]);
        }
        System.out.println();
    }

    public static void main(String[] args) {
        String[] s = cin.nextLine().split(" *, *");
        int[] a = convertStr2Int(s);
        int target = cin.nextInt();
        // display(s);
        int index1 = -1, index2 = -1;
        for (int i = 0; i < a.length - 1; i++) {
            for (int j = i + 1; j < a.length; j++) {
                if (a[i] + a[j] == target) {
                    if (index1 == -1) {
                        index1 = i + 1;
                        index2 = j + 1;
                    }
                    if (a[i] < a[j]) {
                        index1 = i + 1;
                        index2 = j + 1;
                    }
                }
            }
        }
        System.out.println("[" + index1 + ", " + index2 + "]");
    }
}

Implement strStr() 字符串

#include <iostream>
#include <cstring>
using namespace std;

void getNext(const char *patten, int next[]) {
    int i = 0, j = -1;
    next[i] = j;
    while (patten[i] != '') {
        while (j >= 0 && patten[j] != patten[i])
            j = next[j];
        ++i; ++j;
        next[i] = j;
    }
}

int kmpSearch(const char *s, const char *p, const int next[]) {
    int i = 0, j = 0;
    int pos = -1;
    while (s[i] != '') {
        while (j >= 0 && s[i] != p[j])
            j = next[j];
        ++i; ++j;
        if (p[j] == '') {
            pos = i - j;
            cout << s[i - j] << endl;;
            return pos;
        }
    }
    return pos;
}

int main() {
    char p[1024], s[1024];
    int *next;
    cin >> s >> p;
    next = new int[strlen(p) + 1];
    getNext(p, next);
    cout << kmpSearch(s, p, next) << endl;
    return 0;
}

Largest Rectangle in a Histogram

建议用栈和队列 :

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        int[] num = {2,1,5,6,2,3};
        System.out.println(largestRectangleArea(num));
    }

    public static int largestRectangleArea(int heights[]) {
        if (heights.length == 0) return 0;
        if (heights.length == 0) return heights[0];
        int ans = 0;
        int n = heights.length;
        int left[] = new int[n + 1];
        int right[] = new int[n + 1];
        processLR(heights, left, right);
        for (int i = 1; i <= n; i++) {
            int tmp = (right[i] - left[i] + 1) * heights[i - 1];
            if (ans < tmp)
                ans = tmp;
        }

        return ans;
    }

    public static int processLR(int heights[], int left[], int right[]) {
        int n = heights.length;
        //用临时数组,设置两个哨兵
        int tempArr[] = new int[n + 2];
        tempArr[0] = -1;
        for (int i = 1; i <= n; i++) tempArr[i] = heights[i - 1];
        tempArr[tempArr.length - 1] = -1;

        for (int i = 1; i <= n; i++) {
            int k = i;
            while (tempArr[i] <= tempArr[k - 1])
                k = left[k - 1];
            left[i] = k;
        }

        for (int i = n; i > 0; i--) {
            int k = i;
            while (tempArr[i] <= tempArr[k + 1])
                k = right[k + 1];
            right[i] = k;
        }


        return 0;
    }
}
原文地址:https://www.cnblogs.com/jlxuqiang/p/4515985.html