LeetCode算法题 第一天

有时间就刷两道算法题

1.Two sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
题意大概就是给一个Int数组, 给一个结果值, 输出两两相加为结果值的数字。

以下为我的解法:

public void twoSum(int[] nums, int target) {

    int num = nums.length;
    for (int i = 0; i < num; i++) {
        int a = nums[i];
        for (int j = i + 1; j < num; j++) {
            int b = nums[j];
            if ((a + b) == target) {
                Log.d(TAG,a + "        "+b);
            }
        }
    }

}

2.Count and say

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...

1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.

Given an integer n, generate the nth sequence.

Note: The sequence of integers will be represented as a string.

题目大意为

“1”开始,1读作1个1,因此输出“11”

“11”读作2个1,因此输出“21”

“21”读作1个2,1个1,因此输出“1211”

依次类推

以下为我的答案,跟网上的大神对比,我的逻辑比较复杂,效率较低,但我还是把它记录下来,因为是第一反应下写出的逻辑

private void getInterger(int n) {

    String a = "1";
    String outputString = "";
    for (int i = 0; i < n; i++) {
        outputString = "";
        int num = a.length();
        Log.d(TAG, "a: "+a);
        String b = "";
        String c = "";
        int k = 1;
        if (num == 1) {
            outputString = "11";
            a = outputString;
            continue;
        }
        for (int j = 0; j < num; j++) {

            b = a.substring(j,j+1);
            if (j+2 > num) {
                if (b.equals(c)) {
                    outputString = outputString+k+b;
                }else {
                    outputString = outputString + "1"+b;
                }
                a = outputString;
                continue;
            }
            c = a.substring(j+1,j+2);
            if (b.equals(c)) {
                k++;
            }else {
                outputString = outputString+k+b;
                k = 1;
            }
        }
    }
    Log.d(TAG, "getInterger: " + outputString);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值