Author:龙箬 Data Science and Big Data Technology Change the world with data! CSDN@weixin_43975035 算法刷题,坚持下去,就是胜利
LeetCode
两数之和
代码如下:
public class TwoSum {
public int[] twoSum(int[] nums,int target){
int i,j;
int [] array=new int[2];
for (i=0;i<nums.length-1;i++){
for (j=i+1;j<nums.length;j++){
if (nums[i]+nums[j]==target) {
array[0] = i;
array[1] = j;
}
}
}
return array;
}
public static void main(String[] args){
TwoSum heap=new TwoSum();
int[] a={2,8,7,15};
int[] arr=heap.twoSum(a,9);
int i;
for (i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
}
删除排序数组中的重复项
代码如下:
import java.util.Arrays;
public class removeDuplicates {
public static int[] nums={0,1,1,2,7,4,4,5,4};
public static void main(String[] args){
Arrays.sort(nums);
removeDuplicates(nums);
}
public static void removeDuplicates(int[] nums){
int i=0;
for(int j=1;j<nums.length;j++){
if(nums[j]!=nums[i]){
i++;
nums[i]=nums[j];
}
}
System.err.print((i+1)+", nums = [");
for (int k=0;k<i;k++){
System.out.print(nums[k]+",");
}
System.out.print(nums[i]+"]");
}
}
AcWing
A + B
代码如下:
import java.util.Scanner;
public class AcWing01 {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int b=sc.nextInt();
int sum=a+b;
System.out.print(sum);
}
}
01背包问题
代码如下:
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner input=new Scanner(System.in);
int N=input.nextInt();
int V=input.nextInt();
int[] weight=new int[N];
int[] value=new int[N];
for (int i=0;i<N;i++){
weight[i]=input.nextInt();
value[i]=input.nextInt();
}
int[][] backpacks=new int[N+1][V+1];
for (int i=1;i<=N;i++){
for (int j=1;j<=V;j++){
backpacks[i][j]=backpacks[i-1][j];
if (j>=weight[i-1]){
backpacks[i][j]=Math.max(backpacks[i-1][j],backpacks[i-1][j-weight[i-1]]+value[i-1]);
}
}
}
System.out.print(backpacks[N][V]);
}
}
二进制中1的个数
代码如下:
class Solution {
public static int NumberOf1(int n){
char[] chs=Integer.toBinaryString(n).toCharArray();
int res=0;
for (int i=0;i<chs.length;i++){
if (chs[i]=='1'){
res++;
}
}
return res;
}
public static void main(String[] args){
Scanner sca=new Scanner(System.in);
int n=sca.nextInt();
NumberOf1(n);
}
}
如有侵权,请联系侵删。 代码如有错误,欢迎留言批评改正。
|