/*自定义导航栏*/

【算法】数据结构面试算法题目

1 数组去重

python实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#调用内置函数去重
def func(str):
    len1=len(str)
    len2=len(list(set(str)))
    print("去重后的结果是:",list(set(str)),"\t去重个数是:",(len1-len2))
#for 循环去重
def func1(str):
    nums=[]
    for n in str:
        if n not in nums:
            nums.append(n)
    print("去重后的结果是:",sorted(nums),"\t去重个数是:",(len(str)-len(nums)))
# while去重
def func2(str):
    len1=len(str)
    for n in str:
        while str.count(n)>1:
            del str[str.index(n)]
    print("去重后的结果是:",sorted(str),"\t去重个数是:",(len1-len(str)))
 
str=[1,3,2,4,2,4,1,6,4,5]
func2(str)

字典去重

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#调用内置函数去重
def func(str):
    len1=len(str.values())
    len2=len(list(set(str.values())))
    print("去重后的结果是:",list(set(str.values())),"\t去重个数是:",(len1-len2))
#for 循环去重
def func1(str):
    nums=[]
    for n in str.values():
        if n not in nums:
            nums.append(n)
    print("去重后的结果是:",sorted(nums),"\t去重个数是:",(len(str.values())-len(nums)))
 
str=[1,3,2,4,2,4,1,6,4,5]
dirc={1:1,2:2,3:3,4:3}
func2(dirc)

 python字符串追加去重排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#调用内置函数去重
def func(str1,str2):
    print("去重后的结果是:",sorted(set(str1+str2)),"\t去重个数是:",(len(str1+str2)-len(set(str1+str2))))
 
#for 循环去重
def func1(str1,str2):
    nums=[]
    str=str1+str2
    for n in str:
        if n not in nums:
            nums.append(n)
    print("去重后的结果是:",sorted(nums),"\t去重个数是:",(len(str)-len(nums)))
# while去重
def func2(str1,str2):
    str=str1+str2
    for n in str:
        while str.count(n)>1:
            del str[str.index(n)]
    print("去重后的结果是:",sorted(str),"\t去重个数是:",(len(str1+str2)-len(str)))
 
str1=['很好','不错','很好','Very','Book','I','Love','I']
str2=['Java','C#','Python','C#']
func2(str1,str2)

 

 

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import java.util.LinkedList;
import java.util.List;
 
 
public class func {
    public static void unique(String[] str){
        // array_unique 
        List<String> list = new LinkedList<String>(); 
        for(int i = 0; i < str.length; i++) {
            if(!list.contains(str[i])) { 
                list.add(String.valueOf(str[i])); 
            
        
        System.out.print("去重后的结果:"+list+"\t 共去重个数:"+(str.length-list.size()));
    }
    public static void main(String[] args){
        String[] str={"1","3","2","4","2","4","1","6","4","5"};
        unique(str);
    }
 
}

 set实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.util.HashSet;
import java.util.Set;
 
public class func {
    public static void unique(String[] str){
        Set<String> set = new HashSet<String>();
        for (int i=0; i<str.length; i++) {
            set.add(str[i]);
        }
        System.out.print("去重后的结果:"+set+"\t 共去重个数:"+(str.length-set.size()));
    }
    public static void main(String[] args){
        String[] str={"Python","SQL","C#","Java","C","Python","R","Matlab","C++","SQL"};
        unique(str);
    }
}

java字符串追加去重实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/* package whatever; // don't place package name! */
 
import java.util.*;
import java.util.Set;
import java.util.HashSet;
import java.lang.*;
import java.io.*;
 
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    /**
     * 两个数组合并去重
     * 2016年11月5日12:43:34
     * 白宁超
     * str1   long[]  数组1
     * str2   long[]  数组2
    */
    public static void disstr(long[] str1,long[] str2 ){
        if(str1.length<=0||str2.length<=0){
            return;
        }
        long[] str= new long[str1.length+str2.length]; 
        System.arraycopy(str1, 0, str, 0, str1.length); 
        System.arraycopy(str2, 0, str, str1.length, str2.length);
        Set<Long> set=new HashSet<Long>();
        for(int i=0;i<str.length;i++){
            set.add(str[i]);
        }
        System.out.print("追加去重后的数据是:\t"+set+"\n\t\t去重个数:\t"+(str.length-set.size()));
    }
     
 
    public static void main (String[] args) throws java.lang.Exception
    {
        long[] str1={10,20,30,50,10,60,40,20};
        long[] str2={50,60,90,80,70};
        disstr(str1,str2);
    }
}

 

2  求数组中逆序对的总数,如输入数组1,2,3,4,5,6,7,0  逆序对7

Python实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 求数组中逆序对的总数,如输入数组1,2,3,4,5,6,7,0  逆序对7
def index(str3):
    res=0
    if(len(str3)<0): return 0
    if(len(str3)==0):   return str3[-1]
    else:
        for i in str3:
            if(str3[i]>str3[-1]):
                res+=1
    print(res)
 
str3=[1,2,3,4,5,6,7,0]
#func2(str1,str2)
index(str3)

 

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/* package whatever; // don't place package name! */
 
import java.util.*;
import java.lang.*;
import java.io.*;
 
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void func2(){
        int res=0;
        int[] str={1,2,3,4,5,6,7,0};
        for(int i=0;i<str.length;i++){
            for(int j=i;j<str.length;j++){
                if(str[i]>str[j]){
                    res++; 
                }
            }
        }
        System.out.print(res);
    }
    public static void main (String[] args) throws java.lang.Exception
    {
        func2();
    }
}

 3 无序数组A,找到第K个最大值,复杂度小于O(NlgN)

Python实现

方法一:时间复杂度set()*sorted()的复杂度

1
2
3
4
5
6
7
8
9
10
11
12
# 无序数组A,找到第K个最大值,复杂度小于O(NlgN)
def Maxnum(str,n):
    if n>len(str) or n<0:
        print("输入不合法")
        return 0
    numArr=sorted(set(str))
    m=-n
    print(numArr[m])
 
 
str3=[1,2,3,4,5,6,7,0]
Maxnum(str3,30)

 方法二:时间复杂度O(n)+sorted()复杂度

1
2
3
4
5
6
7
8
9
10
11
12
13
def Maxnum1(str,n):
    newstr=[]
    if n>len(str) or n<=0:
        print("输入不合法")
        return 0
    else:
        for i in str:
            if i not in newstr:
                newstr.append(i)
    print(sorted(newstr)[-n])
 
str3=[1,2,3,4,5,6,7,0]
Maxnum1(str3,1)

 方法三:时间复杂度O(nlogn)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
def bnc_quick(arr,low,high):
    if low < high:
        key=arr[low]
        left=low
        right=high
        while low < high:
            while low < high and arr[high] >= key:
                high -= 1
            arr[low]=arr[high]
            while low < high and arr[low] <= key:
                low += 1
            arr[high]=arr[low]
        arr[low]=key
        bnc_quick(arr,left,low-1)
        bnc_quick(arr,low+1,right)
         
arr=[20,10,30,40,100,60,90,210]
print(arr)
bnc_quick(arr,0,len(arr)-1)
n=3
print(arr[-n])

 方法四:时间复杂度O(n)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from random import randint
def findKthMax(l,k):
    if k>len(l):
        return
    key=randint(0,len(l)-1)
    keyv=l[key]
    sl=[i for i in l[:key]+l[key+1:] if i<keyv]
    bl=[i for i in l[:key]+l[key+1:] if i>=keyv]
    if len(bl)==k-1:
        return keyv
    elif len(bl)>=k:
        return findKthMax(bl,k)
    else:
        return findKthMax(sl,k-len(bl)-1)

 方法五:时间复杂度O(n)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
def base_quick(arr,low,high):
    if low < high:
        key=arr[low]
        left=low
        right=high
        while low < high:
            while low < high and arr[high] >= key:
                high -= 1
            arr[low]=arr[high]
            while low < high and arr[low] <= key:
                low += 1
            arr[high]=arr[low]
        arr[low]=key
        return low
         
def findmax(arr,k):
    length = len(arr)
    low = 0
    high = length - 1
    midkey = base_quick(arr, low, high)
    while midkey != k:
        if midkey > k:
            midkey = base_quick(arr, low, midkey - 1)
        elif midkey < k:
            midkey = base_quick(arr, midkey + 1, high)
    return arr[-k:]

 

Java实现

 方法一:时间复杂度O(NlgN)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/* package whatever; // don't place package name! */
 
import java.util.*;
import java.lang.*;
import java.io.*;
 
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void quickSort(int[] arr,int low,int hight){
        if(low < hight){
            int key=arr[low];
            int left=low;
            int right=hight;
            while(low < hight){
                while(low < hight&&arr[hight] >= key){
                    hight--;
                }
                arr[low]=arr[hight];
                while(low <hight&&arr[low] <= key){
                    low++;
                }
                arr[hight]=arr[low];
            }
            arr[low]=key;
            quickSort(arr,left,low-1);
            quickSort(arr,low+1,right);
        }
    }
    public static void main (String[] args) throws java.lang.Exception
    {
        // your code goes here
        int[] arr={1,3,4,6,7,99,45,26};
        for(int i:arr){
            System.out.print(i+" ");
        }
        System.out.println("\n**************************************");
        quickSort(arr,0,arr.length-1);
        for(int i:arr){
            System.out.print(i+" ");
        }
        System.out.println("\n**************************************");
        int k=3;
        for(int i=0;i<arr.length;i++){
            if(i==arr.length-k){
                System.out.print("\n第"+k+"个最大数是:"+arr[arr.length-k]);
            }
     
        System.out.println("\n***************   }***********************");
        int n=3;
        System.out.print("前"+n+"个最大数是:\n");
        for(int i=arr.length-1;i>=arr.length-n;i--){
            System.out.print(arr[i]+" ");
        }
    }
}

 

4 排序算法

Python实现冒泡排序

1
2
3
4
5
6
7
8
9
10
def buttle(arr):
    length = len(arr)
    for i in range(0,length):
        for j in range(i+1,length):
            if(arr[i]>arr[j]):
                arr[i],arr[j]=arr[j],arr[i]
    print(arr)
             
str3=[1,2,13,4,15,6,7,0]
buttle(str3)

 

Java实现冒泡排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static void buttle(int[] arr){
    int temp=0;
    for(int i=0;i<arr.length;i++){
        for(int j=i+1;j<arr.length;j++){
            if(arr[i]>arr[j]){
                temp=arr[j];
                arr[j]=arr[i];
                arr[i]=temp;
            }
        }
    }
    for(int n:arr){
        System.out.print(n+" ");
    }
}

Python实现快排:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
def bnc_quick(arr,low,high):
    if low < high:
        key=arr[low]
        left=low
        right=high
        while low < high:
            while low < high and arr[high] >= key:
                high -= 1
            arr[low]=arr[high]
            while low < high and arr[low] <= key:
                low += 1
            arr[high]=arr[low]
        arr[low]=key
        bnc_quick(arr,left,low-1)
        bnc_quick(arr,low+1,right)
         
arr=[20,10,30,40,100,60,90,210]
print(arr)
bnc_quick(arr,0,len(arr)-1)
print(arr)

 

Java实现快排:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/* package whatever; // don't place package name! */
 
import java.util.*;
import java.lang.*;
import java.io.*;
 
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void quickSort(int[] arr,int low,int hight){
        if(low < hight){
            int key=arr[low];
            int left=low;
            int right=hight;
            while(low < hight){
                while(low < hight&&arr[hight] >= key){
                    hight--;
                }
                arr[low]=arr[hight];
                while(low <hight&&arr[low] <= key){
                    low++;
                }
                arr[hight]=arr[low];
            }
            arr[low]=key;
            quickSort(arr,left,low-1);
            quickSort(arr,low+1,right);
        }
    }
    public static void main (String[] args) throws java.lang.Exception
    {
        // your code goes here
        int[] arr={1,3,4,6,7,99,45,26};
        for(int i:arr){
            System.out.print(i+" ");
        }
        System.out.println("\n**************************************");
        quickSort(arr,0,arr.length-1);
        for(int i:arr){
            System.out.print(i+" ");
        }
    }
}

简单选择排序:

1
2
3
4
5
6
7
8
def select(arr):
    for i in range(0,len(arr)):
        min=i
        for j in range(i+1,len(arr)):
            if arr[min] > arr[j]:
                min=j
        arr[min],arr[i]=arr[i],arr[min]
    return arr

 

 

5 不借助中间变量的两数字交换:

方法一:

1
2
3
4
5
6
private static void swapBySelf(int a, int b) { 
    // 在不引入其它变量的情况下交换两个数,利用两数之和来做 
    a = a+b;   //a保存两数之和 
    b = a-b;    //两数之和-b,即为a 
    a = a-b;    //两数之和-b,此时的b已经变成了a,所以相当于sum-a=b 
}

 

方法二:

1
2
3
4
5
//还有另一种方法,利用两数之差,即两数之间的距离 
a = b-a;   //a=两者的差 
b = b-a;    //b = 原来的b-两数的距离==原来的a 
a = a+b;    //最终的a=两者之差+原来的a==原来的b 
System.out.println("swapBySelf second function:a="+a+",b="+b);//又换回来了 

 

方法三:

1
2
3
4
5
6
7
8
9
//已知x^k^k==x,即一个数与任意一个数作两次异或运算都会变成原来的自己 
private static void swapByXOR(int a, int b) { 
    // 在不引入其它变量的情况下交换两个数,利用异或来做 
    a = a^b;   //a保存两数异或的中间结果 
    b = a^b;    //a两次异或b就变成原来的a,并将其赋值给了b 
    a = a^b;    //b两次异或a就变成原来的b,并且将其赋值给了a 
    System.out.println("swapByXOR first function:a="+a+",b="+b); 
       

 

posted @   伏草惟存  阅读(1179)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示