leetcode 35,38

35Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Example 1:

Input: [1,3,5,6], 5
Output: 2

Example 2:

Input: [1,3,5,6], 2
Output: 1

给一个排序数组找出目标数字在数组中的位置

方法一

  for(int i=0;i<nums.length;i++)
        {
            if(nums[i]==target) return i;
            if(target<nums[i])  return i;
                
        }
        return nums.length;

小改进

  

public int searchInsert(int[] nums, int target) {
    for (int i = 0; i < nums.length; i++) {
        if (nums[i] >= target)
            return i;
    }
    return nums.length;
}

方法2

  public int searchInsert(int[] nums, int target) {
        int head=0;
        int  tail=nums.length-1;
        int mid=-1;
        while(head<=tail)
        {
             mid=(head+tail)/2;
            if(target==nums[mid])
            {
                return mid;
            }
            else if(target>nums[mid])
            {
                head=mid+1;
            }
            else
            {
                tail=mid-1;
            }
        }
        return head;
       
    }

38Count and Say

The count-and-say sequence is the sequence of integers with the first five terms as following:

1.     1
2.     11
3.     21
4.     1211
5.     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 term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

Example 1:

Input: 1
Output: "1"

Example 2:

Input: 4
Output: "1211"

给11122213322字符串 按照如下读法  1有3个;2有3个;1有1个;3有2个;2有2个读取转换成字符串1323113222

现在给字符串1 照上述方法读取n次返回结果

 public String countAndSay(int n) {
          String res="1";
		   for(int i=1;i<n;i++)
		   {
			   res=get(res);			   
		   }
		   return res;
    }
    
     String get(String str)
	    {
	    	char temp=str.charAt(0);
	    	int count=0;
	    	StringBuffer sb = new StringBuffer();
	    	for(int i=0;i<str.length();i++)
	    	{
	    		if(str.charAt(i)==temp)
	    		{
	    			count++;
	    		}
	    		else
	    		{
	    			sb.append(count).append(temp);
	    			temp=str.charAt(i);
	    			count=1;
	    		}
	    	}
	    	sb.append(count).append(temp);
	    	
	    	return sb.toString();
	    }


猜你喜欢

转载自blog.csdn.net/pipiang/article/details/80074015